0

I am using \Drupal::EntityTypeManager() in Drupal 8 to save data provided from a form into a content type. The following code saves the information in the content type news:

$data = [
  'type' => 'news',
  'title' => $title,
  'body' => ['value' => $content, 'format' => $format],
];

$node = \Drupal::EntityTypeManager()
  ->getStorage('node')
  ->create($data);
$node->save();

Now I need to get the nodeID of the node that was just saved. How do I do that ? Furthermore, I need to insert another set of data into a second content type that needs to store the nodeID I just mentioned.

$node2 = \Drupal::EntityTypeManager()
  ->getStorage('node')
  // $data2 contains the $node->id()
  ->create($data2);
$node2->save();

Outside of Drupal I am used to mysql transactions to make sure that both things only get stored together and get rolled back if there is an error with either of them. Is there a way to achieve this 'all-or-nothing' functionality with \Drupal::EntityTypeManager()?

Do I genrally need to put this in a try{}catch{} block in Drupal?

2
  • Isn't it added to the object you just saved? Did you try calling $node->id(); to fetch the node id?
    – Kevin
    Oct 24, 2017 at 15:21
  • absolutely correct, I missed that
    – theuni
    Oct 24, 2017 at 15:40

1 Answer 1

1

You can create the node without saving it. You wouldn't really need a try catch if you know what types of data you're saving.

    $node = \Drupal::EntityTypeManager()->getStorage('node')->create([
      'type' => 'news',
      'title' => "hello world",
      'field_some_textfield' => "Here's some text",
    ]);

    $node->set('status', 1);
    $node->set('field_site_section', [['target_id' => 6]]);
    $node->set('field_first_name', $data->firstName);
    if (!empty($data->middleName)) {
      $node->set('field_middle_name', $data->middleName);
    }
    $node->set('field_last_name', $data->lastName);

When you're satisfied that your node is set up properly, then you can call:

$node->save();

At this point, you can get the node id this way:

$nid = $node->id();
2
  • Nice, I did not know that before. But how does this make sure that for the 2 nodes ($node and the second $node2 I need to save) I have a transaction kind of behavior? Doing $node->save(); $node2->save(); isn't really robust in case things break after $node->save(), is it ?
    – theuni
    Oct 24, 2017 at 15:49
  • The only way to get a node id to add to $node2 is to save the first node. So you could add a code that would run $node->delete() if updating $node2 failed.
    – oknate
    Oct 24, 2017 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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