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?
$node->id();
to fetch the node id?