Skip to main content
update drupal field

Drupal 7 - How to programatically update field value

In general, we can use node_save to save a new node or alter the existing node and then save the changes. Since the topic here is about programmatically updating field value, let us look at an example rather going deep into node_save.

  $node = node_load($nid);
  $node->fieldname['und'][0]['value'] = 'field value';

Using node_save is a good idea, but when you want to update a single field value for all the content of content type, then it is better to give a second thought about it. Consider a case where the site admin would get notified on changing the node content, and there are some thousand nodes in your site, then it is troublesome for site admin. In this case, it is better to go for some lighter alternative and field_attach_update comes to our rescue.

field_attach_update saves the field data for an existing entity. It saves the field data value instead of the entire node, by doing so we can save a lot of time. Check out the syntax of the API function below:

field_attach_update($entity_type, $entity);

where $entity_type can be 'node', 'user', 'comment', and $entity should be entity with field values.

Let us see an example for updating a single field value for a particular content type:

$article_nodes = node_load_multiple(array(), array('type' => 'article'));
foreach ($article_nodes as $article_node) {
  $article_node->body[LANGUAGE_NONE][0]['value'] = 'body value';
  field_attach_update('node', $article_node);

In the above example, we load all the 'article' nodes and change the body field value.

Note: When calling this function outside an entity save operation be sure to clear caches for the entity.