2

I need to load an entity definition to add a constraint and test it, I found that this is possible with the following code:

$manager = \Drupal::entityDefinitionUpdateManager();
$entity_definition = $manager->getEntityType('node');
$entity_definition->addConstraint(‘name’);

But I wonder if this is the correct way or if exists another.

  • Are you using that code in a test? If yes, I don't see anything wrong with using the entity update service. – kiamlaluno Aug 14 '18 at 16:47
  • Differently, if the code is not used inside hook_update_N(), one of the hooks that allows to alter an entity definition should be used. – kiamlaluno Aug 14 '18 at 16:49
  • @kiamlaluno yes I will use the code in a test to test a constraint added to the node entity. – Adrian Cid Almaguer Aug 14 '18 at 16:57
  • @kiamlaluno but this is the only way to get the entity definition or there is another service to do it? – Adrian Cid Almaguer Aug 14 '18 at 17:23
  • To update an entity definition, that is the service you should use. – kiamlaluno Aug 14 '18 at 18:09
0

The only case where you want to work with entityDefinitionUpdateManager() in update and post update hooks, to update an entity type definition on existing installations to the one defined on the annotation.

To add a constraint to an entity type that's not yours use hook_entity_type_alter()

| improve this answer | |

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.