1

I am having trouble updating custom fields programmatically. The code appears below and is in the body of my custom module. When I run this changing the title, it changes OK. But, when I try to do this with the custom field, the field doesn't get updated and I don't understand why. Should I be wrapping this into some hook? Is there a cache not being cleared somewhere? Basically, what am I missing when it comes to programmatically updating fields.

$nodes_to_load = $query->execute();
if (isset($nodes_to_load['node'])) {
  $nodes = entity_load('node', array_keys($nodes_to_load['node']));

  foreach ($nodes as $node) {
  $node->field_myother_field[$node->language][]['value'] = '500';
  $node->title = "retest the test";
  node_save($node);
 }
}
 else {
  print "no nodes to load";
}

UPDATE: When I try to change the field by going into the admin panel, and simply typing in a new value I get a "The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved" error.

1 Answer 1

3

I suspect you don't have $node->language set, or perhaps the empty [] is causing trouble.

Try:

$result = $query->execute();
if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    // Set node language to default, if not set
    $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;
    $node->field_myother_field[$node->language][0]['value'] = '500';
    $node->title = 'retest the test';
    node_save($node);
  }  
}else {
  drupal_set_mesage('no nodes to load');
}

Using entity_metadata_wrapper

$result = $query->execute();
if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    $node_wrapper = entity_metadata_wrapper('node', $node); // Get node wrapper
    $node_wrapper->field_my_other_field->set('500'); // Set field value
    $node_wrapper->save(); // Save entity
  }
}else {
  drupal_set_mesage('no nodes to load');
}
3
  • Worked, thanks. But wow I am getting frustrated with working with fields in Drupal. I understand why the arrays are nested so deeply, but there has to be a better way...
    – RedRaven
    Feb 10, 2013 at 23:24
  • 1
    There is a better way, use entity_metadata_wrapper and field->set($value); Feb 11, 2013 at 0:17
  • 1
    Answer updated to include entity_metadata_wrapper solution. Feb 11, 2013 at 2:19

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.