Hello everyone, maybe someone came across a situation when it is necessary to validate one field and depending on the type of user validation is needed or not.

In my cases there is a User object, it has a "name" field and a "type" field, a "type" field can be natural, juridical, and so I need to make sure that for natural on the name field, validation does not work, but for legal it works like

* @UniqueEntity("name") 

How can I do that?

    1 answer 1

    Try ValidationGroups. Your class:

     <?php namespace AppBundle\Entity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * Class MyClass * @package AppBundle\Entity * @UniqueEntity(fields={"name"},groups={"juridical"}) */ class MyClass { /** * типа enum */ const TYPE_NATURAL = 'natural'; const TYPE_JURIDICAL = 'juridical'; /** * @var string Имя */ private $name; /** * @var string Тип */ private $type; ....... } 

    Your form:

     <?php namespace AppBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use AppBundle\Entity\MyClass; class MyClassType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name', TextType::class); //что-то еще } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'validation_groups' => function (FormInterface $form) { $data = $form->getData(); if (MyClass::TYPE_NATURAL === $data->getType()) { return ['Default','juridical']; } return ['Default', 'natural']; }, ]); } }