EntityTypeManager database transaction 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' =&gt; 'news',
  'title' =&gt; $title,
  'body' =&gt; ['value' =&gt; $content, 'format' =&gt; $format],
];

$node = \Drupal::EntityTypeManager()
  -&gt;getStorage('node')
  -&gt;create($data);
$node-&gt;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()
  -&gt;getStorage('node')
  // $data2 contains the $node-&gt;id()
  -&gt;create($data2);
$node2-&gt;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?
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()-&gt;getStorage('node')-&gt;create([
      'type' =&gt; 'news',
      'title' =&gt; "hello world",
      'field_some_textfield' =&gt; "Here's some text",
    ]);

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


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

$node-&gt;save();


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

$nid = $node-&gt;id();