1

I'm creating a form with Symfony, its works perfectly but I have an issue with my validation, I made a field required and not blank but the error message isn't displayed when I submit the form with the input empty I don't know why

there is some part of code :

FormType :

use Symfony\Component\Validator\Constraints\NotBlank;

class AnnonceurType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
      <some fields>
            ->add('phone', TextType::class, [
                'required' => true,
                'constraints' =>[
                    new NotBlank()
                ]
            ])
     }
}

template of form :

{{ form_start(form) }}
 <some fields>
        <div class="form-group">
            {{ form_label(form.phone, 'Phone number') }} *
            {{ form_widget(form.phone, { 'attr': {'class': 'form-control'}}) }}
        </div>

        <div class="float-right">
            <button type="submit" class="btn btn-primary">
                  {{ 'submit'|trans() }}
            </button>
        </div>
        <div class="form-error">
            {{ form_errors(form) }}
         </div>
   
{{ form_end(form) }}

Someone know what's wrong with my code ? thanks you

update: solved, it was because of the required, I added a novalidate and now its ok

1 Answer 1

3

The function form_errors will output the errors associated with an specific field. In this case, as the root form doesn't have any error, it shows nothing.

You can either:

  • Render the error individually by field: form_errors(form.phone).
  • Use the option error_bubbling in your form fields, so the error does bubble up to the parent and works as you expect.

Additionally, as you seem to be using bootstrap, you can configure the form_theme to use the bootstrap layout; it'll automatically output the field errors as part of the form_label call, although you'll lose the ability to fine control their rendering.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried to render the error with form_errors(form.phone), but the error still not displayed, I didn't configured the form_theme with the bootstrap layout, it is the problem ?
@yonea Try installing a theme, it should help. Add this to the beginning of the twig file {% form_theme form 'bootstrap_4_layout.html.twig' %}
I tried to add like you said, and in config/twig.yaml but errors message still not displayed, very strange
I solved it, it was because of the no validate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.