0

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.

1

1 Answer 1

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.