Profile picture for user admin
Daniel Sipos
11 Mar 2020

In this short article I wanted to draw your attention to a neat little feature introduced in Drupal 8.8 related to migrations. And I mean the ability to force entity validation whenever Migrate saves destination entities.

As we already know, entities can be validated using their typed data wrappers like so:

$violations = $entity->validate();

This calls the general validation over the entity and all its fields. Very handy.

Something that you may or may not know is that when we create and save an entity programatically, this validation is not run by default. So for example:

$entity = Node::create([
  'type' => 'page',
  'title' => 'My title',
]);

$entity->save();

If we had some validation on the title field, it would not run and potentially bad data would be saved in the field. Sometimes this is fine, other times it’s bad and in many times it’s critical as things can break spectacularly. So always good to run validation.

When it comes to the Migrate entity destination, there was no validation being run. But with Drupal 8.8, we have a destination plugin option that indicates we want to run the validation when saving the entity. Like so:

destination:
  plugin: 'entity:node'
  validate: true

This will ensure the nodes are validated before being saved by the migration.

Moreover, apart from the configuration on the migration plugin, you can also control this from the entity level if the entity type is defined by you. You can do this by implementing the Drupal\Core\Entity\FieldableEntityInterface::isValidationRequired() method in the entity class. Do note, however, that most entity types do not implement it, nor is this method checked before doing regular entity saves. I expect its use will be extended but so far it is only used within the migration context.

Hope this helps.

Profile picture for user admin

Daniel Sipos

CEO @ Web Omelette

Danny founded WEBOMELETTE in 2012 as a passion project, mostly writing about Drupal problems he faced day to day, as well as about new technologies and things that he thought other developers would find useful. Now he now manages a team of developers and designers, delivering quality products that make businesses successful.

Contact us

Add new comment