chicken burger
chicken burger

Reputation: 774

How to add an error to a constraint in form?

Using Symfony 3.2 on Ubuntu 16.04

I created a FormType.php with several fields. One of them is a phone number, so I added a constraint where only numbers could be accepted. Here is the code for the phone form

->add('authorPhone', NumberType::class, array('label' => 'Numéro de téléphone',
                'required' => true,
                'attr' => array(
                    'class' => 'validate',
                    'id' => 'icon_telephone'
                ),
                'constraints' => array(new Regex("#^0[1-9]([-. ]?[0-9]{2}){4}$#"))
            ))

After that, in my controller I added an error to tell that numbers only need to be filled in

public function indexAction()
    {
        $form = $this->createForm(FormType::class);
        $form->get('authorPhone')->addError(new FormError('error message'));

        return $this->render('app/main/index.html.twig', array(
            'form' => $form->createView()
        ));
    }

But when I look at my page the error message is actually showing without having filled the field. And of course I don't want that.

image

(you can see under "Numéro de téléphone", which means phone number)

I only want numbers in my phone number field, and if there are letters, an error should be displayed or something saying it's not right.

Upvotes: 0

Views: 2655

Answers (1)

Jan Rydrych
Jan Rydrych

Reputation: 2258

Standard how to to this stuff in Symfony is to define an entity with contraints and error messages and then create entity bound form which will handle validation based on entity's contraints automatically.

But if you need, for some reason, independent form, it can be done to. The addError() method is for adding error "state" the the form field (e.g. for own validation) and you're adding the error by default right after the form is created. That's the reason why the error shows constantly.

UPDATED:

The right way to assign an error message to a form field is by the invalid_message property (which is showed when the entered value doesn't correspond with the field type). But when there's a constraint used for validation, then the err message has to be set according to the constraint validator - so, in your case, by associative array with pattern and message keys.

Next thing need to be corrected is TextType instead of NumberType, because when the NumberType is used, then it won't allow to enter dashes and also automatically trims leading zeros in numbers - so bad for phone numbers :-)

->add('authorPhone', TextType::class, array(
    'label' => 'Numéro de téléphone',
    'required' => true,
    'attr' => array(
        'class' => 'validate',
        'id' => 'icon_telephone'
    ),
    'constraints' => array(new Regex(
        array(
            'pattern' => '#^0[1-9]([-. ]?[0-9]{2}){4}$#',
            'message' => 'Phone error message'
        )
    )),
))

And last thing to review - in the controller (after form declaration) has to be form submission handling routine:

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
....

You can learn more in Symfony's form submission handling: http://symfony.com/doc/current/forms.html#handling-form-submissions

Form rendering is fairly simple. Twig syntax to render whole form:

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

or, if you want to selectively render fields one by one:

{{ form_start(form) }}
{{ form_row(form.authorPhone) }}
{{ form_row(form.submit) }}
{{ form_end(form) }}

It'll renders complete field including labels and errors

Upvotes: 1

Related Questions