Search code examples
phpsymfonyoopsymfony2

Impossible to customise error message on email field on Sf2


I modify my code to follow @Stony advices.

I would like to customise my email input error. I try to follow the symfony2 tutorial but it doesn't work.

I follow symfony validation tutorial and I create my yml file, but when I fill my email fiel with bad adress, the error display is still the symfony default error and not my custom message...

/**
 *
 * @Route("/info")
 */
class InfoController extends BaseController
{
    public function contactusAction(Request $request)
    {   
    $constraint = new Collection(array('email' => new Email(array('message' => 'Adresse email invalide')),));

    $contact = new ContactUs(); 
    $form = $this->createFormBuilder($contact)
        ->add('nom', 'text')
        ->add('mail', 'email')
        ->add('sujet', 'choice', array('choices' => array('pt' => 'Problemes techniques', 'bi' => 'Boite a idees', 'd' => 'Divers')))
        ->add('msg', 'textarea')
        ->getForm();
    }
}

Here is my view

<form action="" method="post" {{ form_enctype(form) }} class="contactus">
        {{ form_errors(form) }}
        <div>
            {{ form_label(form.nom, 'Nom : ') }}
            {{ form_errors(form.nom) }}
            {{ form_widget(form.nom) }}
            </div>
            <div>
            {{ form_label(form.mail, 'Email : ') }}
            {{ form_errors(form.mail) }}
            {{ form_widget(form.mail) }}
            </div>
        <div>
            {{ form_label(form.sujet, 'Sujet : ') }}
            {{ form_errors(form.sujet) }}
            {{ form_widget(form.sujet) }}
            </div>
        <div>
            {{ form_label(form.msg, 'Message : ') }}
            {{ form_errors(form.msg) }}
            {{ form_widget(form.msg) }}
            </div>
        <input type="submit" value="Envoyer" />
        {{ form_rest(form) }}
    </form>

Here is my yml file

PROJECT\CoreBundle\Entity\ContactUs:
    properties:
        mail:
            - Email:
                message: Adresse email invalide.

Solution

  • I think the error message is very clear:

    $form = $this->createFormBuilder($contact, array('constraints' => $constraint))
    

    there is no second option constraint. I don't know what your goal is but this is not the correct way.

    If you want some validation you should look at Creating Form Classes in your Tutorial. There you can see how you can define Form and Type classes and how to set validation on the fields.

    Some more information: Validation