9

I have an admin user id 15, How to load the model to get username and user role? In Magento1 this was possible using:

$adminuserId = 15;
Mage::getModel('admin/user')->load($adminuserId)->getRole()->getData();

How does it work in Magento2?

0

3 Answers 3

22

You need to add this to your class and constructor:

protected $userFactory;
public function __construct(
    ...
    \Magento\User\Model\UserFactory $userFactory,
    ...
)
{
    ...
    $this->userFactory = $userFactory;
    ...
}

Then create a method in the same class to retrieve the role data:

public function getRoleData($userId)
{
    $user = $this->userFactory->create()->load($userId);
    $role = $user->getRole();
    $data = $role->getData();
    return $data;
}
4

You can use following code:

$adminuserId = 15;
$user = \Magento\Framework\App\ObjectManager::getInstance()->create(
    'Magento\User\Model\User'
);
$user->load($adminuserId);

But it is not recommended to use ObjectManager directly in the code. Try to add Magento\User\Model\UserFactory to your class constructor and use it to load customer.

Example:

class SomeMyClass
{
    protected $_userFactory;

    public function __construct(
        \Magento\User\Model\UserFactory $userFactory
    ) {
        $this->_userFactory = $userFactory;
    }

    public function someFunction()
    {
        $adminuserId = 15;
        $user = $this->_userFactory->create();
        $user->load($adminuserId);
    }
}
-2

The following will help to get the magento logged user id. Thank you

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$extensionUser = $objectManager->get('Magento\Backend\Model\Auth\Session')->getUser()->getUsername();
$extensionId = $objectManager->get('Magento\Backend\Model\Auth\Session')->getUser()->getID();
1
  • 1
    ObjectManager is deprecated, Please don't use it.
    – Matias
    Commented Oct 14, 2020 at 17:10

Your Answer

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

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