How can I alter the title of a node upon save? I want to automatically set the title of nodes with content type ABC to the node ID.  (I want to hide the title field from the form in the UI, and I don't care about titles for this content type.)

For now, I am putting in dummy data (Title and Body) to test this.

At first I tried hook_ENTITY_TYPE_presave():

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity-&gt;getType() == 'ABC') {
    $entity-&gt;setTitle($entity-&gt;id());
  }
}


However, this fails because the entity ID has not yet been assigned.  So next I tried hook_ENTITY_TYPE_insert():

/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function mymodule_node_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity-&gt;getType() == 'ABC') {
    $entity-&gt;setTitle($entity-&gt;id());
  }
}


This does not result in an error, and I get the status message ABC 23 has been created. However, the node title shows the dummy title I entered, not the node ID.  I tried to fix this by adding $entity-&gt;save() to the insert() hook, but this results in a duplicate key error.

How can I change the node title to the node ID upon saving the node for the first time?
I'm not sure why exactly you need the ID, if you don't care about it, wouldn't the date or something like that suffice too?

If you really want the ID, then you need both hooks, because you can't save the node without a title. So you need to set a dummy title in presave and update it again in insert. I'm not sure why saving there didn't work for you, it should, I've done similar things. If you provide the full exception message and stack trace, maybe I can help figure it out. Note that by default the sql content entity storage catches the thrown exception and re-throws a different one and our exception handling can't handle that. You need to print out the original exception stack trace where that happens, with print $e-&gt;getTraceAsString().