3

I need to do some processing (calculate a zodiac sign) on some user data after an account is saved. (When saving a user account, I want to use a custom module to re-compute a field and save the new value.)

I have a function MYMODULE_calculate_zodiac() which returns the term ID of the user's zodiac sign. I have used dpm() to confirm that the correct value is calculated.

Here is the function in my custom module:

function MYMODULE_user_update(&$edit, $account, $category) {
  global $user;
  $user = user_load($account->uid);

  $zodiac_sign = MYMODULE_calculate_zodiac($account);
  $edit['field_zodiac']['und'][0]['tid'] = $zodiac_sign;

  user_save($account, $edit);
}

However, when I save a user account with this code, my site just hangs and the user is not saved (error: Fatal error: Maximum execution time of 240 seconds exceeded). What am I doing wrong?

6

The problem there is you're creating an endless loop.

user_save calls hook_user_update, your hook_user_update calls user_save.... you get the picture.

A better approach would be to use

hook_user_presave

to add the field, then you don't need to worry about saving the account, as the user module will do that for you after the field is added.

The downside is, the uid isn't available in presave (for new accounts), though for a zodiac sign, I assume that's not required.

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.