Simple way to differentiate both hooks is the 'ID' is not available in hook_entity_presave() ("pre meaning before, and without saved ID is not assigned in database),
But this 'ID' will be available in hook_entity_insert().
Example:
function mymodule_node_insert(NodeInterface $node) {
$nid = $node->id();
}
OR
function mymodule_node_insert($node) {
if ($node->getType() == 'your content type') {
$node->setTitle('New entity ' . $node->id()); // to update title with node id
$node->field_test = 'Id' . $node->id(); // or, to update a text field with node id
$node->save();
}
}
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityType()->id() == 'node') {
$entity->setTitle('New Title here');
//Note : Not to save, because it's automatic.
}
}
OR
function mymodule_node_presave(Drupal\node\NodeInterface $node) {
$node->setTitle('Edited Title');
$node->set('body', 'this is the new body section');
//Note : Not to save, because it's automatic.
}
Note: If have any suggestions or issue regarding 'Difference between hook_entity_presave and hook_entity_insert ?' then you can ask by comments.
But this 'ID' will be available in hook_entity_insert().
Example:
function mymodule_node_insert(NodeInterface $node) {
$nid = $node->id();
}
OR
function mymodule_node_insert($node) {
if ($node->getType() == 'your content type') {
$node->setTitle('New entity ' . $node->id()); // to update title with node id
$node->field_test = 'Id' . $node->id(); // or, to update a text field with node id
$node->save();
}
}
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityType()->id() == 'node') {
$entity->setTitle('New Title here');
//Note : Not to save, because it's automatic.
}
}
OR
function mymodule_node_presave(Drupal\node\NodeInterface $node) {
$node->setTitle('Edited Title');
$node->set('body', 'this is the new body section');
//Note : Not to save, because it's automatic.
}
Note: If have any suggestions or issue regarding 'Difference between hook_entity_presave and hook_entity_insert ?' then you can ask by comments.