S
S
serverkon2013-09-21 17:13:26
Drupal
serverkon, 2013-09-21 17:13:26

User roles vs hook_user_presave

A warning! This question will be answered immediately. It's just that the proposed text below somehow does not pull on a full-fledged article.

In general, hook_user_presave is a rather capricious thing, and if you work with the $account object, and not with the $edit array, you need to save the user profile twice in order to properly process the hook.

Conditions:


  1. Used by hook_user_presave ;
  2. This hook uses the $edit array to be used in a function that manipulates the user's data.
  3. The function from point 2 uses
    user_access('administer role',$edit);
    

Problem:


user_access('administer role',$edit);

will return TRUE in any case (it actually returns an array where it is indicated that the user has access rights to anything).

Task:

Make sure the $edit['roles'] array is correct for the user_access() function;

Decision:


Add the following code to the hook:
foreach($edit['roles'] as $key=>$val){
  if((bool)$val){
    $role = user_role_load($key);
    $edit['roles'][$key] = $role->name;
  }
  else{
    unset($edit['roles'][$key]);
  }
}
unset($key,$val);

Profit!

PS I spent several hours searching for a solution to the problem without such a "bicycle". If you know how to solve this problem more beautifully, I ask for answers.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question