Introducing Drupal 8's Entity Validation API
Feature
Drupal 8 comes with plenty of new features: the high visibility ones, like CKEditor or Views in core, and those less obvious but equally pivotal to Drupal 8’s strength and flexibility, like the Entity Validation API.
Never heard of it? You're not alone – much of the fanfare around Drupal 8 is devoted to the shiny parts. But under the hood, rock solid developer APIs like the Entity Validation API are what will make Drupal 8 a pleasure to work with for client projects and contributed modules alike.
So what is this Entity Validation API and why should you care?
For Those Who Came in Late
In Drupal versions up to and including Drupal 7, any validation was done in the Form API. Consider the Comment entity, provided by the Comment module. There is a lot of validation relating to comments, such as:
- If the comment is being updated, we confirm the timestamp is a valid date.
- If the comment is being updated and the username is changed, we confirm the username is valid.
- If the comment is anonymous, we validate that the name used for the comment doesn't match an existing username.
- If the comment is anonymous, we confirm that the e-mail address entered is valid.
- If the comment is anonymous, we confirm that the homepage is a valid URL.
In Drupal 7 and earlier all of this happens in the comment form validation logic, in comment_form_validate()
.
The issue here is that this validation is tied to a form submission. If you're saving a comment via some other method, then you have to duplicate all this logic to ensure you don’t end up with invalid comment entities. Common alternate methods include:
- using Rules;
- using a Restful, Services, or Rest WS endpoint;
- programmatically saving via custom code;
- using a custom comment form.
The same scenario is repeated for Nodes, Users, Taxonomy terms, and custom Blocks (which aren’t entities per se in Drupal 7, but the story is the same).