I use hook_ENTITY_TYPE_presave()
and hook_ENTITY_TYPE_insert()
in order to update the node with a title using its ID.
function <module_name>_node_presave($node) {
// ...
if ($node->isNew() && $node->getType() == '<custom_content_type>') {
$node->title = 'New entity ' . $node->id()->value;
}
}
function <module_name>_node_insert($node) {
if ($node->getType() == '<custom_content_type>') {
$node->title = 'Submission #' . $node->id();
// more code...
$node->save();
}
}
The first setting of title in hook_ENTITY_TYPE_presave()
is only done because no entity can be saved without title. However, it seems like the setting of the title in hook_ENTITY_TYPE_insert()
does not change anything.
I have already tried calling node->save();
in hook_ENTITY_TYPE_insert()
but it gives me an exception stating that I try to store an entity using an already existing primary key. The exception message is
The website encountered an unexpected error. Please try again later.
Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '48' for key 'PRIMARY': INSERT INTO {node_revision} (nid, vid, langcode, revision_timestamp, revision_uid, revision_log) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 45 [:db_insert_placeholder_1] => 48 [:db_insert_placeholder_2] => en [:db_insert_placeholder_3] => 1485011236 [:db_insert_placeholder_4] => 11 [:db_insert_placeholder_5] => ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Can I change the title of the new entity (using the id)? Should I use another hook?
node->id()
returns an integer not an object.