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.