Drupal 8 Entity Validation and Typed Data Demonstration
In the previous article of this series we’ve started our dive into the Entity Validation and Typed Data APIs. We’ve seen how
DataType plugins interact with data definitions and how various constraints can be added to the latter at multiple levels and extension points.
In this part, we will cover the aspect of actual validation and violation handling. In addition, we will write our own constraint and validator so that we can use custom behaviors in the data validation process.
Validation and Violation Handling
Even though we don’t yet know exactly how constraints are built, we’ve seen how they can be added to Typed Data definitions, including entity fields. Let us now see how we can validate the entities and handle possible violations we find.
When talking about Typed Data we’ve already seen how the
validate() method can be called on the
DataType plugin instance which holds a data definition. When it comes to entities, this can happen both at entity and field levels.
For instance, we can validate the entire entity using the
$entity->set('title', 'this is too long of a title'); $violations = $entity->validate();
In our previous article, we added the
Length constraint to Node titles to prevent title strings longer than 5 characters. If that is still in place and we run the code above, the validation should obviously fail. The
$violations object is now, however, an
EntityConstraintViolationListInterface instance which provides some helper methods for accessing violation data specific to Drupal content entities. It’s worth looking into that interface for all the helper methods available.
To get a list of Entity level violations we can use the
getEntityViolations() method but we can also loop through all of them. Once we have our individual
ConstraintViolationInterface instances, we can inspect them for what went wrong. For instance, we can get the error message with
getMessage(), the property path that failed with
getPropertyPath() and the invalid value with
getInvalidValue(), among other useful things.
When it comes to fields, the property path is in the following format:
title.0.value. This includes the field name, the key (delta) of the individual field item in the list and the actual property name. This represents the property path of our violation above.
Apart from calling validation on the entire entity (which may be superfluous at times), we can also do so directly on each field:
$entity->set('title', 'this is too long of a title'); $violations = $entity->get('title')->validate();
In this case,
$violations is again an instance of
ConstraintViolationListInterface and can be looped over to inspect each violation. This time, though, the property path changes to no longer include the field name:
Continue reading %Drupal 8 Entity Validation and Typed Data Demonstration%