-->

Form does not display form errors in template

2019-04-15 22:49发布

问题:

For my contact form no form errors are displayed.

    $contact = new Contact();

    $form = $this->createForm(new ContactFormType(), $contact);

    /* handle contact form submission */
    if ('POST' == $request->getMethod()) {
        $form->bindRequest($request);

        if ($form->isValid()) {
            //Do something
        }
    }

    return $this->render('MainBundle:Default:contact.html.twig', array(
                'form' => $form->createView()
    ));

My validator

Fc\MainBundle\Entity\Contact:
    properties:
        firstName:
            - NotBlank: ~

        lastName:
            - NotBlank: ~

        email:
            - NotBlank: ~
            - Email:
                checkMX: true
        title:
            - NotBlank: ~
        message:
            - NotBlank: ~

I have added a novalidate attribute to my form tag to check if my validation works. Now when I submit the form with empty data nothing happens (with correct data everything is fine), the controller identifies the form as invalid and stops further processes.

In the template I call

 {{ form_errors(form) }}

But nothing is displayed. Any ideas why? I use symfony 2.1.X

回答1:

Can you confirm that the validation is working with this:

if ($form->isValid()) {
//Do something
}
else
{ die('not valid') }

Is the form well posted?

Is there anything in the HTML that shows up where you call {{ form_errors(form) }} ? - it would be a CSS or JS problem if that's the case...

Have you tried to show the errors by field (there is no global error in your validation apparently):

{{ form_errors(form.firstName) }}
etc.

Remark: form.firstName works, not form.first_name. You have to follow that convention with Doctrine2/Symfony2.