0

I use this:

$values = array(
  'type' => 'competition',
  'title‎' => 'my title goes here',
);
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

This works perfectly. But the problem is, I also have a node reference field called "field_competition_node_reference‎". But this doesnt work:

$values = array(
  'type' => 'competition',
  'title‎' => 'my title goes here',
  'field_competition_node_reference‎' => 1,
);

How would one go about doing this? The value on the object is "target_id". Maybe that's why "create()" doesnt work?

2 Answers 2

0

This should work :

$values = [
  'type' => 'competition',
  'title‎' => 'my title goes here',
  'field_competition_node_reference‎' => [['target_id' => 1]],
];
Node::create($values);
0
  $node = Node::create([
      'type' => 'competition',
      'title' => 'my title goes here',
       'field_competition_node_reference‎' => [
         'target_id' => 1,
       ],
    ]);
    $node->save();

Another way to create node with reference field is:

$node = \Drupal::entityTypeManager()->getStorage('node')->create(array(
  'type'        => 'competition',
  'title'       => 'my title goes here',
  'field_competition_node_reference‎' => [
    'target_id' => 1
  ],
));
$node->save();

Don't forget Add namespace.

  use \Drupal\node\Entity\Node;

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.