Score:0

How can I set validation rules on my entity fields and get errors if the data isn't valid

ye flag

I have this entity which got the link field

This link is mandatory, has to be more than 3 chars and less than 255 Also it has to be a valid URL

class Myentity extends ContentEntityBase implements BaseEntityInterface {

  use EntityChangedTrait;

  public static function baseFieldDefinitions( EntityTypeInterface $entity_type )
  {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['link'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Url'))
      ->setDescription(t('The entity url.'))
      ->setSettings(
        [
          'default_value' => '',
          'min_length' => 3,
          'max_length' => 255,
          'text_processing' => 0,
        ]
      )->setRequired(true)
      ->addConstraint('Length', ['min' => 3, 'max' => 255]);

  }


}

And then somewhere in the application, I want to save that entity

$data = ['link': 'X'];

$entity = Myentity::create($data);

$violationList = $entity->validate();

echo $violationList->count(); //Prints 0 ! although the length isn't good!

setRequired(true) guarantees me that the field link is mandatory

addConstraint('Length', ['min' => 3, 'max' => 255]) Doesn't seem to work, As I didn't get any error while validating my data

So I've some questions about this code:

  1. How do we set the validation rules for an entity, I saw two functions addConstraint and setPropertyConstraints. which one to use or there is another way ?

  2. After validating data, and if $violationList->count() is positive, How do we get the rules that failed, I know $violationList->getFieldNames() returns the invalid field but not the rule that failed.

  3. And last, what are the rules that Drupal 9 provides, are they the ones that are shipped with the Symfony Validator components as stated in Drupal's documentation OR there is a defined list.

apaderno avatar
us flag
The *string* entity field has only the *max_length* setting, and that works, as it's used from [`Node::baseFieldDefinitions()`](https://api.drupal.org/api/drupal/core%21modules%21node%21src%21Entity%21Node.php/function/Node%3A%3AbaseFieldDefinitions/9.3.x). There is no need to add a constraint for that, which is already added from [`StringItem::getConstraints`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Plugin%21Field%21FieldType%21StringItem.php/function/StringItem%3A%3AgetConstraints/9.3.x).
Score:2
ph flag

I use addConstraint in my custom entities and haven't had a problem. I see your field definition is for "name" but your data says "link", maybe that's why?

Here's a snippet for getting the errors:

    $violations = $entity->validate();
    $errors = [];
    foreach ($violations as $violation) {
      $property = $violation->getPropertyPath();
      $field = explode('.', $property)[0];
      $label = $entity->get($field)->getFieldDefinition()->getLabel();
      $errors[] = $label . ': ' . $violation->getMessage();
    }

There's a list of core constraints here:

https://api.drupal.org/api/drupal/vendor!symfony!validator!ConstraintValidator.php/class/uses/ConstraintValidator/9.3.x

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.