I created a custom entity and want to programmatically set the title based on 2 other properties.

For example, the entity has year and state properties. When the entity is created, I want to populate the title property with year state.

How can I achieve this?

  • Try hook_entity_presave() or if only on creation hook_entity_insert(). – Patrick Kenny Dec 7 '17 at 13:56
  • Thanks for the suggestion. Since I created this entity myself, it really seems like this should be achieved in the entity source, vs the module. Is that not the case? – Coder1 Dec 7 '17 at 13:59

For a custom entity type, you can override EntityStorage::doPreSave() in your entity class:

function doPreSave(EntityInterface $entity) {

  // Perform field manipulation here.

  return $entity->id();
  • Thanks. Just before I saw this, I got public function preSave(EntityStorageInterface $storage) to work. I went back and tried your suggestion though and the changed property would not save. I'm unsure what the difference between doPreSave and preSave is. – Coder1 Dec 7 '17 at 14:47
  • 1
    It depends - preSave is called (by doPreSave as it happens) before hook_ENTITY_TYPE_presave is invoked. If that's the flow you need, use preSave. If you'd rather run your presave code after all other modules have got involved via the hook, use doPreSave and run the parent method before your own code – Clive Dec 7 '17 at 15:28

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.