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->getType() == 'ABC') {
$entity->setTitle($entity->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->getType() == 'ABC') {
$entity->setTitle($entity->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->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?