Search code examples
drupaldrupal-6cckdrupal-node-hook

How do I set the value for a CCK Node-reference field automatically when create form submits


I have a content type (A) that references a single node of a different content type (B). The node referenced (B) can be programmatically determined using the information for the user creating this new node (A)... Each user can only create a single node of the referenced content type (B), so this single node will always be referenced from nodes of content type B that the user creates.

Because the referenced node is always known, I don't want the user to have to enter the reference value, I want to set it for them behind the scenes. I've found a number of threads about doing this, but none seem to be clear or actually work for me.

Any help would be greatly appreciated.

Note: Drupal 6


Solution

  • You can try:

    function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
       switch ($op) {
          case 'insert':
             if ($node->type == 'type_a') {
                $node->field_of_reference[0]['nid'] = 'node reference value';
                node_save($node);
             } 
             break;
       }
    }
    

    This should add the value to the node and save it after it has been created.

    http://api.drupal.org/api/function/hook_nodeapi

    Note: You will need to create a module to facilitate this. You can also try the Rules module, though, I am not sure it will do what you ask without a custom rule. But I know the above method will work.