0

I am validating csv files. I am thinking of using constraints and constraint validator framework available in Drupal to validate the data in the files. However, these seem to be designed to be attached to entity fields. For example.

/** Implements hook_entity_base_field_info_alter(). */ function projectname_commerce_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) { if ($entity_type->id() === 'commerce_order_item') { if (!empty($fields['unit_price'])) { $fields['unit_price']->addConstraint('PriceBelowMax'); } } } 

where PriceBelowmax is a custom constraint. I would like to attach this constraint to a custom data array. For example

myCustomValidatemethod($data_array, $constraints) 

where constraints would be the list of constraints defined in Drupal both core and custom. Is there some reference for the above method.

1 Answer 1

2

You cannot validate generic data against a list of constraints you create.

Constraints are attached to specific typed data objects, entity fields, or entities. You can only validate them against the constraints they have, and you don't need to get first the list of the constraints that apply.

If $entity contains an entity, you can use the following code to check if it validates against its constraints.

$violations = $entity->validate(); if ($violations) { // The entity didn't pass validation from constraints. // For each validation $validation->getMessage() returns the // error message. $violation->getPropertyPath() returns the property // path for the property that failed validation, for example // field_text.0.value, if the validation failed for the value property of // field_text. } 

To validate only a single entity field, for example field_text in $entity, instead of $entity->validate(), which would validate the entity and all its entity fields, the method to call is $entity->field_text->validate().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.