0

I would like to add a form validation to an entity edit form. The entity has an entity_reference field on which I would like to perform a manual validation. I have successfully implemented a hook function to access the data entered into the widget, perform the required checks, and raise an error if necessary. The problem is that I do not want to make my function dependent on the widget that is used to alter the entity_reference field.

An entity_reference field with cardinality bigger than 1 (i.e. the ability to store a list of entries) can be edited using, e.g., an Autocomplete, an Autocomplete (Tag Style) or a Select List. The problem is that the data accessible in the validation function will differ depending on what widget is used.

The function $form_state->getValue('field_name') returns either

Array ( [0] => Array ( [target_id] => 2 ) [1] => Array ( [target_id] => 3 ) )

or

Array ( [target_id] => Array ( [0] => Array ( [target_id] => 2 ) [1] => Array ( [target_id] => 3 ) ) ) 

For a select_list or an autocomplete_tag, respectively.

I could obviously check what the structure of the array is to determine how to handle it, but I'm sure there must be a better way to obtain the data from this array.

My custom validation involves a check to be performed on a relation between the referenced entities and the user, so I do not need to perform any checks on the entered raw data. Basically, I just want to obtain a list of target_id's that I can interact with.

0

The solution was to implement entity-level constraints. This allows Drupal to manage the data that gets typed into the widgets, and no additional (widget-dependent) validation is necessary.

Apparently, the idea in Drupal 8 is that most entity-related validations are not done via the form validations. Instead, so-called constraints can be added, either on the field level to affect only one field, or on the entity level to affect multiple fields.

This GitHub repo contains example files for creating entity-level constraints, which were very helpful. You will need to create files for the Constraint and for its Validator. Furthermore, you will need to attach the Constraint to the Entity, which can be done either using hooks (as demonstrated in the .module file, see link above) or by adding this to the annotations of your entity:

 *   constraints = {
 *     "ExampleConstraint" = {}
 *   }

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.