0

I am trying to change a field value inside both hook_node_insert() and hook_node_update() using EMW. It actually changes the original $node object that is passed to these hook functions but the change doesn't get saved at the end.

function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type'); 

  $messagew->field_hidden_type = $nodew->field_hidden_type->value();//this actually works
  $messagew->save();
}

There are a few questions near to this one actually, but none of them addresses this precisely. This one for example is a very good explanation of the mechanism but its suggestion it not use.

Here, one should not use $nodew->save(), because it causes infinite loop. I also played a little with module weight, that does not help either.

I also tried to change another entity reference field. No use.

I don't want to go with field_attach_update() because it is old-fashioned.

2
  • 1
    Try hook_node_presave()
    – Clive
    Commented Apr 19, 2015 at 23:40
  • Thank you @Clive. I am about to implement this. Everything points to this direction.
    – duru
    Commented Apr 20, 2015 at 15:15

1 Answer 1

0

The method you are using the save the field isn't ideal.
For setting the field values you should use the set() function provided by the EntityMetadataWrapper class.

function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type'); 

  $messagew->field_hidden_type->set($nodew->field_hidden_type->value());
  $messagew->save();
}

On a side note, I see that there is not check on the node type, or any other parameters in the implementation of hook_node_insert. Note that it will get triggered every time a node of any content type is created.

1
  • thank you for the suggestion. set() and = are both same and = is preffered on account of code readibility. Pleaser refer to http://www.mediacurrent.com/blog/entity-metadata-wrapper. Also, the first line calls a custom check function. I deleted lots of lines for better readibility.
    – duru
    Commented Apr 20, 2015 at 15:14

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.