0

I try to add a new role programmatically using this code :

<?php 
    namespace ModuleNameSpace\YourModuleName\Setup; 

    use Magento\Framework\Setup\InstallDataInterface;
    use Magento\Framework\Setup\ModuleContextInterface;
    use Magento\Framework\Setup\ModuleDataSetupInterface; 

    /* For get RoleType and UserType for create Role */; 
    use Magento\Authorization\Model\Acl\Role\Group as RoleGroup;
    use Magento\Authorization\Model\UserContextInterface;
    /** * @codeCoverageIgnore */ 

    class InstallData implements InstallDataInterface { 

    /** * RoleFactory * * @var roleFactory */ 
    private $roleFactory; 

    /** * RulesFactory * * @var rulesFactory */ 
    private $rulesFactory; 

    /** * Init * * @param \Magento\Authorization\Model\RoleFactory $roleFactory * @param \Magento\Authorization\Model\RulesFactory $rulesFactory */ 

    public function __construct( 
    \Magento\Authorization\Model\RoleFactory $roleFactory, /* Instance of Role*/
 \Magento\Authorization\Model\RulesFactory $rulesFactory /* Instance of Rule */ 
/*this define that which resource permitted to wich role */ ) { 
    $this->roleFactory = $roleFactory; 
    $this->rulesFactory = $rulesFactory; 
    } 

    /** * {@inheritdoc} * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ 

    public function install(
    ModuleDataSetupInterface $setup,
    ModuleContextInterface $context) { 
    /** * Create Warehouse role */
   $role=$this->roleFactory->create();
   $role->setName('YourRoleName') //Set Role Name Which you want to create 

   ->setPid(0) //set parent role id of your role 
   ->setRoleType(RoleGroup::ROLE_TYPE) 
   ->setUserType(UserContextInterface::USER_TYPE_ADMIN); 

    $role->save(); 
    /* Now we set that which resources we allow to this role */ $resource=[
        'Magento_Backend::admin',
                    'Magento_Sales::sales'
       ]; 

    /* Array of resource ids which we want to allow this role*/ 
    $this->rulesFactory->create()->setRoleId($role->getId())->setResources($resource)->saveRel(); 
    } 
    }

and I run the setup:upgrade command, but when I go to the User roles I can't found it.

PS: my module setup is '0.0.0.1'

is there any solution?

1 Answer 1

0

I fixed the issue by deleting the row modul on setup_model table on database

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.