0

I need to capture the entity_id when the entity is saved. The ID will process and insert in a custom field. I use hook_entity_presave(), but when is a new entity the ID is void. Is there any way to capture the ID?

/**
 * Implements hook_entity_presave().
 */
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity_type = $entity->getEntityType()->id();
  if(($entity_type === 'node' || $entity_type === 'taxonomy_term')) {
    $entity->field_custom_token->value = _process_token($entity->id()); // if entity is new, the ID is Null :(
  }
}
2

Try changing your code to use hook_entity_insert which is run after the saving to the database: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_insert/8.2.x

As the reason you can't get the entity ID in presave is because if its a new entity then the ID hasn't been generated by the autoincrement ID field in the database yet so an ID doesn't exist for it until it's saved for the first time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.