Magento – How to assign role to admin user Programmatically

magento-1.7role

I need to assign a user role to admin user programmatically. How can I? I tried some methods like,

try {
$user->setRoleIds(array(<role_id>))
    ->setRoleUserId($user->getUserId())
    ->saveRelations();

} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}

But when we apply the above code, the database get corrupted and gets an Error – "Parent Role id 'G5' does not exist".

This is because, when I apply the above code, the admin user with parent role Id is get deleted and I cant access the database If I recreate it again!

Can anyone point out a solution?

Best Answer

It seams you are doing it OK. It all depends on the values you use.
This piece of code worked for me. Assuming $id is the admin id in question:

$user = Mage::getModel('admin/user')->load($id);
$user->setRoleIds(array(5))
    ->setRoleUserId($user->getUserId())
    ->saveRelations();

5 is the id of the role. It even works with a role id that does not exist. It just removes any role from the admin user.

Related Topic