Programmatically Create New Admin User Role in Magento 2

Magento 2 provides the in-built feature on the admin side to create a new admin user role, and if you want to know about that, here is my previous blog “Steps to Create a New Admin User Role in Magento 2” which helps you. But in some cases like building extensions, you may want to create an admin user role programmatically by using an installable script. Thus here is the blog with simple steps that will guide you to develop an installable script easily.

Step 1: Module Registration

In order to create a new module in Magento 2, first, create new PHP file named registration.php as follows,

Sample file path: app/code/BlogTreat/NewUserRole/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'BlogTreat_NewUserRole',
    __DIR__
);

Step 2: Define the New Module

Then, create an XML file named module.xml in the following file path to define the new module,

Sample file path: app/code/BlogTreat/NewUserRole/etc/module.xml

Here, we have to specify our custom module’s name like BlogTreat_NewUserRole and it’s setup version as below,

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="BlogTreat_NewUserRole" setup_version="1.0.0">
    </module>
</config>

Step 3: Create a Setup File

Finally, Create a setup file InstallData.php in the below file path, and in this file, we have to provide the information about new admin user role,

Sample file path: app/code/BlogTreat/NewUserRole/Setup/InstallData.php

<?php
namespace BlogTreat\NewUserRole\Setup;
 
use \Magento\Framework\Setup\InstallDataInterface;
use \Magento\Framework\Setup\ModuleDataSetupInterface;
use \Magento\Framework\Setup\ModuleContextInterface;
use \Magento\Authorization\Model\Acl\Role\Group as RoleGroup;
use \Magento\Authorization\Model\UserContextInterface;
use \Magento\Authorization\Model\RoleFactory;
use \Magento\Authorization\Model\RulesFactory;

class InstallData implements InstallDataInterface
{
    /**
     * RoleFactory
     *
     * @var roleFactory
     */
    private $roleFactory;

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

    /**
     * Init
     *
     * @param RoleFactory $roleFactory
     * @param RulesFactory $rulesFactory
     */
    public function __construct(
        RoleFactory $roleFactory,
        RulesFactory $rulesFactory
    ) {
        $this->roleFactory = $roleFactory;
        $this->rulesFactory = $rulesFactory;
    }

    public function install(
        ModuleDataSetupInterface $setup, 
        ModuleContextInterface $context
    ) {
        $role = $this->roleFactory->create();
        $role->setName('YourNewAdminRoleName')
                ->setPid(0)
                ->setRoleType(RoleGroup::ROLE_TYPE) 
                ->setUserType(UserContextInterface::USER_TYPE_ADMIN);
        $role->save();

        $resource = [
            'Magento_Backend::admin',
            'Magento_Sales::sales',
            'Magento_Sales::create',
            'Magento_Sales::config_sales'
        ];
        $this->rulesFactory->create()
                ->setRoleId($role->getId())
                ->setResources($resource)
                ->saveRel();
    }
}

After completing the above steps run the below SSH command in your Magento 2 installed root directory,

php bin/magento setup:upgrade

Then, clear all the Magento cache and check whether the new admin user role has been successfully created on Magento 2 admin by navigating to Magento 2 Admin > System > Permission > User Role.

Note: We have tested the above code on Magento 2.3.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *