1

I have read this post fast saving single field value about how to use field_attach_update to save nodes without the overhead of node_save().

I would like to use this for users (which it should work for, as per https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field_attach_update/7) . However, I'm not sure how to apply the examples to users.

Currently, this is my code:

if (isset($uid)) {
    $user = user_load($uid);
    $user_og_groups = $user->og_user_node[LANGUAGE_NONE];
    $user_committee_positions = $user->field_committee_position_serno[LANGUAGE_NONE];
    $user_data = my_module_import_user($cust_info, $cust_attributes, $drupal_countries, $employers);
    $user = user_save($user, $user_data);
  }

The $user_data variable is an array of data, which is what user_save expects (https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_save/7). user_save() doesn't work exactly the same as node_save() and doesn't accept a user object.

How then can I use field_attach_update to programmatically update users?

1 Answer 1

2

I don't know your function my_module_import_user return right data? I think user_save() work fine. You can try

if (isset($uid)) {
  $account = user_load($uid);
  $edit = array();
  $edit['field_FIELD_NAME'][LANGUAGE_NONE][0]['value'] = 'Field Value';
  // add more data
  user_save($account, $edit);
}

if you want use field_attach_update

if (isset($uid)) {
  $account = user_load($uid);
  $account->field_FIELD_NAME[LANGUAGE_NONE][0]['value'] = 'Field Value';
  // add more data
  field_attach_update('user', $account);
}

And my way, i often use Entity metadata wrappers

if (isset($uid)) {
  $account = user_load($uid);
  $wrapper = entity_metadata_wrapper('user', $account);
  //Set data of field
  $wrapper->field_FIELD_NAME->set('Field Value');
  // set more data here
  $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.