0

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?

2 Answers 2

2

I'm not sure why exactly you need the ID, if you don't care about it, wouldn't the date or something like that suffice too?

If you really want the ID, then you need both hooks, because you can't save the node without a title. So you need to set a dummy title in presave and update it again in insert. I'm not sure why saving there didn't work for you, it should, I've done similar things. If you provide the full exception message and stack trace, maybe I can help figure it out. Note that by default the sql content entity storage catches the thrown exception and re-throws a different one and our exception handling can't handle that. You need to print out the original exception stack trace where that happens, with print $e->getTraceAsString().

-1
  • alter your contenty form, using hook_form_alter.
  • print(form); there.
  • you will be able to find the title, like form['title'] .
  • you can set your title there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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