I'm using Drupal 7 and trying to create a node programmatically. Once the node has been created I would like to reference it to an existing node

I'm creating a node programmatically like below

$node = new stdClass();
$node->type = $type;
$node->title = $title;
$node->uid = $user->uid;
//set field values

Which works.

I would then like to update an existing node to reference the newly-created node. I basically load the existing node, get the node id from the newly created node and update the reference field, like below

$node2 = node_load($node2);

$node2->field_reference['und'][0] = array(
  'target_id' => $node,
  'target_type' => 'node',



I get two errors when I add the second part to the code Notice: Undefined property: stdClass::$nid in node_tokens() Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute()

The first part works, the second does not. I'm getting the id of $node2 through tokens.

How can I make this work?

  • $node2 is a node object or node ID?
    – Aboodred1
    Commented Jun 25, 2013 at 19:32
  • 2
    When you are loading node2, shouldn't it be $node2= node_load($node2->nid); ? I see $node2 = node_load($node2);. Also the 'target_id' is $node or $node->nid ? Commented Jun 25, 2013 at 19:47
  • If you have valid answers why not post an answer instead of a comment?
    – rooby
    Commented Jun 26, 2013 at 10:28

2 Answers 2


As for the second part, you need to pass node ID or array of node IDs to node_load function first argument.

Your code should look like the following:

$node2 = node_load($nid); // pass integer node ID or array of integers 

$node2->field_reference['und'][0] = array(
  'target_id' => $node->nid, // pass integer node ID not node object


  • your answer looks fine and also working in my case. I am using 'nid' in place of 'target_id', rest depends on what kind of values this reference field contains. Commented May 20, 2014 at 4:15
  • References module uses nid, Entity Reference target_id.
    – AKS
    Commented Jul 1, 2014 at 6:59

If you are using Drupal 7, I suggest to use entity_type, so you can easly create nodes by fetching a type of entity you have to add[here in your case it is node type]. Easy way and much suitable for your requirement.

If you are interested, look at my answer to the question Fetching more than id's of an entity using EntityFieldQuery on Drupal Answers. Once if you have created an etity_type, then it is up to you. You are always welcome to the world of entities.

Thank you.

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.