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:
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 ?
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.
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.