0

In the node add/edit form, I have a node reference field. When users select a node, I want to update another field with value of a field of selected node.

What's the best and easiest way to do this?

I want to load the value in the edit form, using AJAX or AHAH, so that the users can see it, and edit if necessary, not just updating the field after form is created.

1

Drupal 7:

Create a custom module. This module should implement hook_node_insert and hook_node_update. Both functions will have almost identical code, and it should go something like this:

/**
 * Implements hook_node_insert()
 */
function mymodule_node_insert($node) {
  if ($node->type == 'my_node_type') {
    // Set the $value variable with value you wish
    // to insert to the referenced node.
    $field = field_get_items('node', $node, 'field_whatever_it_is');
    $value = $field[0]['value'];

    // Grab the referenced node's nid.
    $field = field_get_items('node', $node, 'field_nodereference_field_name');
    $ref_nid = $field[0]['value'];

    // Load the referenced node into a variable. Avoid cached nodes.
    $ref_node = node_load($ref_nid, NULL, FALSE);

    // Update the referenced node with $value
    $ref_node->field_to_update[0]['value'] = $value;

    // Save the referenced node
    node_save($ref_node);
  }
}

If you just want to update the referenced node's node reference field with the current node's nid then you can also just use a module called Corresponding Node References

7
  • Thanks, But I want to update field in edit form not just in node view so user can edit the loaded value – hknik Mar 14 '12 at 13:59
  • Yea the above hooks will get called when a node is updated or inserted as new via the node edit form. Isn't that what you need? – Beebee Mar 14 '12 at 14:07
  • No, I want to load value using ajax(ahah) – hknik Mar 14 '12 at 14:12
  • 2
    You never mentioned AJAX or AHAH on your original question. – Beebee Mar 14 '12 at 14:16
  • I edited the question. – hknik Mar 14 '12 at 14:23
0

I think the Rules module can help you.

The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

There is a good screencast about how to have nodes being updated in sync with the parent nodes they belong to.

Sync article promotions with articles

1
  • 2
    This answer would be more helpful, if it would explain exactly how the Rules module help the OP. – apaderno Mar 14 '12 at 15:59

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.