What use function hook_entity_presave In drupal 9

By toswebdev, 27 January, 2022
What use function hook_entity_presave In drupal 9
/**
 * Implements hook_entity_presave().
 */
function drupalbook_examples_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'node' && $entity->getType() == 'article') {
    $entity->title->value = $entity->title->value . 'by ' . date('d-m-Y');
  }
}

Hook_entity_presave () is fired every time an entity is saved.

You don’t need to call $entity-> to save() inside the hook because the entity object will be modified before saving. In this example, we add to the title of the article the current date the node was saved. If we update the article the next day, the new date will be added again. If you do not delete the date from the title before saving, then the title will become newer and newer after re-saving the article. Most often, we check the presence of certain values for fields in the entity when saving, or you can send an email with a notification about the change in the article.

Note that we check the desired entity type first because the code in hook_entity_presave () works for all entities: content, blocks, comments, taxonomy terms. And also check the bundle of nodes we need.

Comments

All comments go through moderation, so your comment won't display immediately.