0

I need to edit a field in contentType B when I create or edit nodes of contentType A.

I know it's possible to use rules for this but I need to have more control so I want to do it in my own module.

Tried this code without success:

function MYMODULE_node_presave($node) {
    MYMODULE_change_value($node);
}

function MYMODULE_change_value($node) {
    $node = node_load($node->nid);

    $referenced_nid = $node->referenced_node[LANGUAGE_NOE][0]['target_id']

    $referenced_node = node_load(referenced_nid);

    $referenced_node->my_field[LANGUAGE_NONE][0]['value'] = 12345.0;
    node_save($referenced_node);
}

Am I choosing the wrong hook?

  • It's D7 or D8 ? – berramou Oct 14 '18 at 20:10
  • Sorry., I always forget. It's D7. – zephirus Oct 14 '18 at 20:27
  • you use this module entityreference module to reference nodes ? – berramou Oct 14 '18 at 20:37
  • Yes. The nodes of contentType B are referenced in nodes of contentType A. – zephirus Oct 14 '18 at 20:39
1

Try the following:

/**
 * Implements hook_node_presave().
 */
function yourModule_node_presave($node) {
  if ($node->type == 'your_typeA') {
    yourModule_change_value($node);
  }
}

function yourModule_change_value($node) {
  if (isset($node->field_node_referenced[LANGUAGE_NONE][0]['target_id'])) {
    //- Get referenced node id
    $referenced_node_id = $node->field_node_referenced[LANGUAGE_NONE][0]['target_id'];
    //- Load referenced node
    $wrapper = entity_metadata_wrapper('node', $referenced_node_id);
    $wrapper->field_name->set(array(
      'value' => 'test new field value'
    ));
    $wrapper->save();
  }
}
  • The field that I want to change is a taxonomy term. Using your code, I get this error: EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at node(26)->my_field: array ( 'tid' => 6, ). I changed your line: 'value' => 'test new field value' to 'tid' => 6 – zephirus Oct 14 '18 at 21:08
  • try with field_name->set(6) without value – berramou Oct 14 '18 at 21:19
  • I was also looking for a solutio and that's exactly what I've found. It depends on the type of value you want to change. Thanks for you support berramou! – zephirus Oct 14 '18 at 21:24
  • you are welcome! – berramou Oct 14 '18 at 22:18
  • I have a related question. I'm passing the $node variable to my "change_value" function. Is it possible to pass also the previous node values? – zephirus Oct 15 '18 at 14:08

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.