21

I want to change the value of a field for a node.I used the following code:


$node = node_load($nid); // $nid is the function's parameter
$node->field['field_myfield'][$node->language][0]['value'] = 1;
node_save($node);

The problem is $node->language returns es while in print_r($node) it's und. Why $node->language is different from what's in $node array and how can I get it?

41
$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_myfield->set(1);
$node_wrapper->save();

Entity metadata wrapper is a great way for set or read values of fields in the node!

  • I prefer entity_metadata_wrapper bc it does make things nice and clean. I would include a check for whether $node exists after the node_load() to avoid a nasty error when inadvertently passing NULL into entity_metadata_wrapper(). – texas-bronius May 8 '14 at 3:44
  • You can directly pass the $nid to EMW. – nawfal Feb 4 '16 at 22:21
  • using entity_metadata_wrapper should be the accepted answer. – akalata Feb 21 '16 at 19:08
  • 2
    In case it's not obvious to others, entity_metadata_wrapper() is part of the Entity API module: drupal.org/project/entity – BWPanda Mar 21 '16 at 23:11
9

Try field_attach_update() function.

$node = node_load($nid); // $nid is the function's parameter
$node->field['field_myfield'][LANGUAGE_NONE][0]['value'] = 1;
field_attach_update('node', $node);

It will update the field's value and it performs better than node_save.

  • 1
    why field_attach_update is downvoted? – milkovsky Feb 22 '16 at 16:30
6
$node = node_load($nid); 
$field_language = field_language('node', $node, 'field_myfield');
$node->field['field_myfield'][$field_language][0]['value'] = 1;
node_save($node);
4

If you want to update only field value (without updating node metadata about updated time, revisions) use function field_attach_update().

Example:

$node = node_load($nid);
$field_language = field_language('node', $node, 'field_myfield');
$node->field_fieldname[$field_language][0]['value'] = 'some value';
field_attach_update('node', $node);

Sometimes additionally you might need to reset node static cache with resetCache(array($nid)):

entity_get_controller('node')->resetCache(array($node->nid));

Source: Saving node's fields without saving the node itself

2

I have just implemented this and found that this code worked for me.

$node = node_load($nid); 
if (isset($node)) {
  $field_language = field_language('node', $node, 'field_myfield');
  $node->field_fieldname[$field_language][0]['value'] = 'some value';
  node_save($node);
}

Note that I when updating field_fieldname I found that using this in line 4

$node->field['field_myfield'][0]['value'] = 'some value';

did not work.

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.