0

Challenge:

  • I have a profile2 taxonomy term reference field (single select) on user profiles called "field_member_interest_group".
  • On save/update of the user profile, I wan to A) See if the user has a role of "Elephant", then if so, select the term of "Elephant Group" from that user's taxonomy term reference field and save the changes.
  • "MYMODULE" is the name of my module in lowercase.

My (not working) Code:

function MYMODULE_user_update(&$edit, $account, $category) {
    $account = user_load($account->uid);
    $profile_profile = profile2_load_by_user($account->uid, 'profile');
    $profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile->pid);

    if (in_array('Elephant', $account->roles)) {  
        $termX = 3942; //tid of "Elephant Group"
    }
    $profile_wrapper->field_member_interest_group->set($termX);

    //Save changes to the profile entity
    $profile_wrapper->save();
}

Problem:

The changes are not saved to the user account, they are ignored completely.

Any thought on what could be going wrong?

3 Answers 3

0

I believe entity_metadata_wrapper expects the second parameter to be an object. As in:

$profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile);
0

A couple of things:

  1. Minor point: In you code $profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile->pid);, since you already have the profile object loaded, you can pass the object itself in rather than the pid.

  2. You say the problem is that changes are not being saved to the user account. Do you mean they are not being saved to the user profile entity? In your code you are using $profile_wrapper->save(); to save the profile entity, but you haven't changed anything on the user account or written any code to save it.

  3. You can try this way of setting the tid: $profile_wrapper->field_member_interest_group = $termX; Other than that, the code looks good.

By the way, Daniel's answer is incorrect. You can use entity_metadata_wrapper with either an entity ID or with an entity object. See: http://www.mediacurrent.com/blog/entity-metadata-wrapper

0

In Drupal 7 you can easily go with:

global $user;
$new_value = "somevalue"; 
module_load_include('inc', 'profile2', 'profile2.admin');
$profile2 = profile2_by_uid_load($user->uid, "main");  
$profile2__wrapper = entity_metadata_wrapper('profile2', $profile2);
$profile2__wrapper->field_ultimo_display->set($new_value);
$profile2__wrapper->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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