1

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?

3

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.

2

Strange! But finaly got a solution from here.

Gave a try catch like this,

         try {
          $role = Mage::getModel("admin/role");
          $role->setParent_id(5);
          $role->setTree_level(1);
          $role->setRole_type('U');
          $role->setUser_id($user_id);
          $role->save();
          echo "Your username: ".$username.", and password: ".$password;
            } catch (Exception $e) {
            echo $e->getMessage();
            }

and it Worked. Here parent Id is my custom role id. $user_id is the id of user to whome role should be attached.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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