Skip to content
Advertisement

Get Symfony form data before building the form

I’m displaying the form on a page by doing this in the controller:

$form = $this->createFormBuilder()
    ->add('email', EmailType::class, [
        'constraints' => [
            new NotBlank(),
            new Email(),
        ]
    ])
    ->add('password', PasswordType::class, [
        'constraints' => [
            new NotBlank()
        ]
    ])
    ->add('passwordRepeat', PasswordType::class, [
        'constraints' => [
            new NotBlank(),
            new EqualTo('VALUE OF PASSWORD'),
        ]
    ])
    ->add('submit', SubmitType::class, [
        'label' => 'Reset',
    ])->getForm();

return $this->render('page/forgot-password.html.twig', [
    'form' => $form->createView()
]);

The problem is that the value of the passwordRepeat input has to be equal to the value of the password input. But in order to get the data from the password input I already have to build the form and then I can’t add the condition anymore.

How can I make sure the value of password can be added as to the EqualTo constraint in passwordRepeat?

Advertisement

Answer

Instead of passing a value, you can use the propertyPath option, that allows you to reference the value of another field in your form:

->add('password', PasswordType::class, [
    'constraints' => [
        new NotBlank()
    ]
])
->add('passwordRepeat', PasswordType::class, [
    'constraints' => [
        new NotBlank(),
        new EqualTo(['propertyPath' => 'password']),
    ]
])
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement