I want to have an admin user who would only be able to view the ‘Images And Videos’ and ‘Search Engine Optimiation’ in the admin product edit form.
I tried the following.
Created app/code/Vendor/Module/view/adminhtml/layout/catalog_product_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="page.main.actions">
<block class="VendorModuleBlockAdminhtmlPermission" name="admin.permission" template="Vendor_Module::product_edit.phtml" after="-" />
</referenceContainer>
</body>
</page>
Created block file app/code/Vendor/Module/Block/Adminhtml/Permission.php
use MagentoBackendBlockTemplate;
use MagentoBackendBlockTemplateContext;
use MagentoBackendModelAuthSession as AdminSession;
class Permission extends Template
{
/**
* Constructor
*
* @param Context $context
* @param AdminSession $adminSession
* @param array $data
*/
public function __construct(
Context $context,
AdminSession $adminSession,
array $data = []
)
{
$this->adminSession = $adminSession;
parent::__construct($context, $data);
}
/**
* @return string
*/
public function getCurrentAdminUserRole()
{
return $this->adminSession->getUser()->getRole()->getRoleName();
}
}
Added template at app/code/Vendor/Module/view/adminhtml/templates/product_edit.phtml
<?php
/**
* @var $block VendorModuleBlockAdminPermission
*/
?>
<script type="text/x-magento-init">
{
"*": {
"adminProductPermission": {
"role":"<?= $block->getCurrentAdminUserRole() ?>"
}
}
}
</script>
Added my js in require js app/code/Vendor/Module/view/adminhtml/requirejs-config.js
var config = {
map: {
'*': {
adminProductPermission:'Vendor_Module/js/permission'
}
}
};
And finally in the JS file app/code/Vendor/Module/view/adminhtml/web/js/permission.js
define([
'jquery'
], function ($) {
return function(config) {
var userRole = config.role;
if(userRole == 'SEO') {
$('.fieldset-wrapper div:not([data-index="gallery"]):not([data-index="search-engine-optimization"])').hide();
}
}
});
This is not working , as I believe the form is being loaded by KO js and it is being loaded after my js executed.