Use entity validation annotations in non mapped form fields

Sometimes you have the situations that the Symfony form mapping does not map to your entity model. In that case you use non mapped fields in your form. With form events you can map the entered data into the (or other) entity. But in this case the annotations for validation are not applied on your mapped field.

But it is possible to use the same constraints in your non mapped form field as in the entity. First inject the Validator into your form type and get the meta data for the entity (or object) that contains the annotations:

class ScoreType extends AbstractType
{
    /**
     * @var ClassMetadata
     */
    private $entityMetaData;
 
    public function __construct(ValidatorInterface $validator)
    {
        $this->entityMetaData = $validator->getMetadataFor(ScoreChange::class);
    }
}

Now get a list of the annotations for the property by selecting it and add all the constraints to a new array.

$constraints = [];
foreach ($this->entityMetaData->getPropertyMetadata('reason') as $set) {
    foreach ($set->getConstraints() as $constraint) {
        $constraints[] = $constraint;
    }
}

Assign this array to the non mapped field:

$builder->add('reason', TextType::class, [
    'mapped' => false,
    'constraints' => $constraints
]);
31-07-2019 EN symfony php forms validation
Deel via: LinkedIn Twitter