1

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;
node_object_prepare($node);
//set field values
node_save($node);

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',
);

node_save($node2);

drupal_goto("node/$node->nid");

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 Jun 25 '13 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 ? – Sandesh Yadav Jun 25 '13 at 19:47
  • If you have valid answers why not post an answer instead of a comment? – rooby Jun 26 '13 at 10:28
1

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
);

node_save($node2);

drupal_goto("node/{$node->nid}");
  • 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. – Pushpinder Rana May 20 '14 at 4:15
  • References module uses nid, Entity Reference target_id. – AyeshK Jul 1 '14 at 6:59
0

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, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.