4

Question: How do I update a single field of an entity? For example, lets say I have a user and want to update field_my_field. How do I just update that without using user_save?

My Specific Problem: I have a a bunch of user fields defined, and am trying to optimize the performance of my site. I am using views_bulk_operations, and my code is timing out (maximum execution time) because I am repeatedly calling user_save, and it's an expensive operation.

I am only updating a single field, and would like to optimize this code. Rather than calling user_save, which is taking 500ms to run, I'd like to update the field directly.

I attempted to use field_attach_update(), and that works a little better, but that's also updating all the fields. Is there any specific way just to update or save a specific field for an entity?

I'm not interested in batch operations, or anything at the moment -- I know how to do that, and can convert this into a batch so I don't run into execution timeouts. I just want to know how to save a single field for an entity.

3 Answers 3

5

Give a try with field_sql_storage_field_storage_write.

See this blog post with an example:

//Get the id of your field
$name = 'name_of_your_field';
$info = field_info_field($field_name);
$fields = array(info['id']); 

//Execute the storage function
field_sql_storage_field_storage_write('model', $entity, 'update', $fields);
2
  • This worked for the most part, thanks. I am running into some caching issues, not sure whether it's with memcache, drupal or APC, but it's out of scope of this question.
    – Foo
    Feb 11, 2013 at 19:36
  • 1
    For future reference, the problem we are facing was with entitycache. Our entity was being cached, and it was displaying the cached version.
    – Foo
    Feb 21, 2013 at 22:44
0

Drupal 7 create new table for each field, there is no entry in this table if value is not available for this field. To save value in this field further use field_attach_update instead node_load.`

$field = new stdClass();
$field->type = 'story_cover'; // content type name
$field->nid = $node->nid; // node id
$field->field_number_of_pages[LANGUAGE_NONE][0]['value'] = 'YOUR_VALUE'; // field name
field_attach_update('node', $field);
1
-1

You have to first load the logged in user and then use entity module function entity_metadata_wrapper to update the user field, but be pretty sure to enable the entity module.

            $account = user_load_by_name($uname);
    $user = user_load($account->uid);
    $obj = entity_metadata_wrapper('user', $user);
    $obj->{field_machine_name}['und']['0']['value'] ="your value" ;
    $obj->save();

Your Answer

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

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