1

My users have 2 fields: 'A' and 'B'. The value of the second one depends on the value of the first one and is set by the following custom module:

function MYMODULE_user_presave (&$edit, $account) {
    $tid = $edit['field_A']['und'][0]['target_id'];
    if (isset ($account->roles[3])) {
        $B = taxonomy_term_load(8);
        }
        else {
            $B = taxonomy_term_load($tid);
        }
    $edit['field_B']['und'][0]['fid'] = $B->field_B['und'][0]['fid'];
}

It works fine, but when an anonymous user registrates himself/herself, it fails: the if is evaluated as true and the new user gets the wrong value in 'B'. When I commented out the if and only left over the else action, it did work, so it has something to do with the $account.

What's going wrong and how can I solve this?

Note: role 3 is the built-in administrator role.


Edit: This is my final code after @m1n0's answer:

function MYHOOK_user_presave (&$edit, $account) {
    $tid = $edit['field_A']['und'][0]['target_id'];
    if ($account->is_new OR !isset ($account->roles[3])) {
        $B = taxonomy_term_load($tid);
        }
        else {
            $B = taxonomy_term_load(8);
        }
    $edit['field_B']['und'][0]['fid'] = $B->field_B['und'][0]['fid'];
}
2
  • Maybe the roles haven't been added to the account object yet, what about something like if (in_array(3, array_filter($edit['roles']))) { ... }?
    – Clive
    Feb 16 '14 at 22:31
  • @Clive: After testing some more times, things turned out a bit different: 'B' gets a value now, but it's the wrong one. I've updated my question.
    – Jeroen
    Feb 16 '14 at 22:37
2

As stated in the documentation (https://api.drupal.org/api/drupal/modules%21user%21user.api.php/function/hook_user_presave/7), you need to check whether the user is being created or not with the following code:

if ($account->is_new)

The reason is that $edit contains the values submitted, and $account contains the existing user data - but on user registration, there is no user that already exists in the database. Your code should check whether new user is being created and in that case assign some default value (like you already have with $B= taxonomy_term_load($tid);)

1
  • 1
    Perfect! I've added my final code in my question for future visitors. (Mind that your link doesn't work correctly anymore...) :)
    – Jeroen
    Feb 16 '14 at 22:49

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.