Настраиваемый валидатор Symfony5 в FormType - поле проверки пароля при установленном флажке - PullRequest
0 голосов
/ 02 мая 2020

Я хотел бы проверить поле ввода пароля в форме, основанной на значении флажка. Если значение TRUE, поля пароля должны быть NOTBlank и равны первому-второму. Это то, что у меня есть:

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;


class UsuarioFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('nombre',null,[
            'required'   => true,
            'constraints'=> [
                new NotBlank([
                    'message' => 'Escriba el nombre por favor',
                ]),
            ]
        ])
        ->add('apellido',null,[
            'required'   => true,
            'constraints'=> [
                new NotBlank([
                    'message' => 'Escriba el apellido por favor',
                ]),
            ]
        ])
        ->add('user_name',null,[
            'required'   => true,
            'empty_data' => '',
            'constraints'=> [
                new NotBlank([
                    'message' => 'Escriba el nombre de usuario por favor',
                ]),
            ]
        ])
        ->add('active', CheckboxType::class, [
            'required' => false
        ])
        ->add('email',EmailType::class,[
            'constraints' => [
                new Email([
                    'mode'=> 'html5',
                    'message' => 'El correo electrónico {{ value }} no es un correo electrónico válido',
                ]),
            ]
        ])        
        ->add('plainPassword', RepeatedType::class, [
            'type' => PasswordType::class,
            'invalid_message' => 'Los campos de contraseña deben ser iguales',
            'mapped' => false,
            'required'   => false,
            'constraints' => [
                new Length([
                    'min' => 6,
                    'minMessage' => 'Your password should be at least {{ limit }} characters',
                    // max length allowed by Symfony for security reasons
                    'max' => 4096,
                ]),
            ],
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'constraints' => [
                new Callback([$this, 'validate']),
            ],
        ]);
    }
    public function validate($data, ExecutionContextInterface $context): void
    {
        if ($data['chk_passUpdate']){
            if (trim($data['plainPassword']['first']) == '' ) {
                $context->buildViolation('El campo de contraseña no puede estar en blanco')
                ->atPath('plainPassword')
                ->addViolation();
            }
            if ($data['plainPassword']['first'] != $data['plainPassword']['second'] ) {
                $context->buildViolation('Los campos de contraseña deben ser iguales')
                ->atPath('plainPassword')
                ->addViolation();
            }
        }
    }
}

Этот код вызывает исключение:

Аргумент 1, переданный в App \ Form \ UsuarioFormType :: validate (), должен иметь тип массив, заданный объект, вызывается в C: \ Csi \ CsiWorkspace \ SynfonyTest \ SymfonyTest \ vendor \ symfony \ validator \ Constraints \ CallbackValidator. php в строке 46

1 Ответ

0 голосов
/ 06 мая 2020

Через неделю я обнаружил, что лучшим решением является использование групп проверки.

Таким образом, мой код будет выглядеть следующим образом:

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\FormInterface;


class UsuarioFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('nombre',null,[
            'required'   => true,
            'constraints'=> [
                new NotBlank([
                    'message' => 'Escriba el nombre por favor',
                ]),
            ]
        ])
        ->add('apellido',null,[
            'required'   => true,
            'constraints'=> [
                new NotBlank([
                    'message' => 'Escriba el apellido por favor',
                ]),
            ]
        ])
        ->add('user_name',null,[
            'required'   => true,
            'empty_data' => '',
            'constraints'=> [
                new NotBlank([
                    'message' => 'Escriba el nombre de usuario por favor',
                ]),
            ]
        ])
        ->add('active', CheckboxType::class, [
            'required' => false
        ])
        ->add('password_update', CheckboxType::class, [
            'required'  => false,
            'mapped'    => false
        ])
        ->add('email',EmailType::class,[
            'constraints' => [
                new Email([
                    'mode'=> 'html5',
                    'message' => 'El correo electrónico {{ value }} no es un correo electrónico válido',
                ]),
            ]
        ])        
        ->add('plainPassword', RepeatedType::class, [
            'type' => PasswordType::class,
            'invalid_message' => 'Los campos de contraseña deben ser iguales',
            'mapped' => false,
            'required'   => false,
            'constraints' => [
                new Length([
                    'min' => 6,
                    'minMessage' => 'Your password should be at least {{ limit }} characters',
                    // max length allowed by Symfony for security reasons
                    'max' => 4096,
                ]),
                new NotBlank([
                    'message' => 'Escriba su contraseña',
                    'groups' => 'password_update'
                ]),
            ],
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'validation_groups' => function(FormInterface $form){
                if ($form['password_update']->getData()){
                    return array('Default', 'password_update');
                }else{
                    return array('Default');
                }
            }

        ]);
    }

}

Таким образом, когда флажок установлен, форма будет проверять 2 группы (по умолчанию и password_udpate). Если она отключена, будет проверена только группа по умолчанию.

Надеюсь, что это поможет кому-нибудь когда-нибудь.

...