Symfony Form Required Only in Custom Validation Fields

I try my best to find a way to make requiredonly those fields that have their own custom validator. Is there any way to achieve this?

/**
 * @var string
 * @ORM\Column(type="string", length=255)
 * @AdminAssert\CustomNotBlank(          // <--- this is my custom validator
 *     groups={
 *         //...
 *     }
 * )
 */
protected $name;

/**
 * @var string
 * @ORM\Column(type="string", length=255)
 * @Assert\Email(
 *     groups={
 *         //...
 *     }
 * )
 */
private $email;

So, in the above example, it $nameshould have 'required' => true, because it was confirmed by my own validator CustomNotBlank. And not a single field that does not have this validator, no matter what other verification parameters they have.

FormType doesn't really matter because I have many fields from many types of forms (this is a simple example of two fields of type text)

+4
source share
1 answer

Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser , :

'Symfony\Component\Validator\Constraints\NotNull'
'Symfony\Component\Validator\Constraints\NotBlank'
'Symfony\Component\Validator\Constraints\IsTrue'

, TypeGuesser, . form.type_guesser.validator guessRequiredForConstraint(), :

public function guessRequiredForConstraint(Constraint $constraint)
{
    switch (get_class($constraint)) {
        case 'Symfony\Component\Validator\Constraints\NotNull':
        case 'Symfony\Component\Validator\Constraints\NotBlank':
        case 'Symfony\Component\Validator\Constraints\IsTrue':
        case 'AppBundle\Validator\Constraints\CustomNotBlank': // <-- adds here
            return new ValueGuess(true, Guess::HIGH_CONFIDENCE);
    }
}

required , .

:

AppBundle\Validator\ValidatorTypeGuesser, , , :

services:
    form.type_guesser.validator:
        class: AppBundle\Validator\ValidatorTypeGuesser
        arguments: ['@validator.mapping.class_metadata_factory']
        tags: ['form.type_guesser']
+3

Source: https://habr.com/ru/post/1683443/


All Articles