mlwacosmos
mlwacosmos

Reputation: 4541

forms and required attribute

I am wondering something. Maybe it is a bug in Symfony, I dont know :

Suppose a Product object :

class Product
{
    private $id;
    private $name;
    private $price;
    private $description;
}

I build a form with this object. Here is my validation file :

myVendor\myBundle\Entity\Product:
  properties:
    name:
      - NotBlank: ~
    price:
      - NotBlank: ~

this is my formbuilder :

$builder->add('name', 'text', array('label' => $this->translator->trans('product.demo.name')));
$builder->add('price', 'money', array(
        'label' => $this->translator->trans('product.demo.price'),
        'invalid_message' => $this->translator->trans('product.demo.validation.price.error')
    ));
$builder->add('description', 'textarea', array('label' => $this->translator->trans('product.demo.description')));

When the form is generated the 3 zones for the fields have a required attribute... even description which is not required.

If I deactivate HTML5, it works good because Symfony look at the validation file and see that description field is not requiered.

But if HTML5 is activated, a description value is requiered because of the required attribute.

Is that a bug of Symfony generating fields with a required attribute by default or something ...

Can it be fixed ?

Thank you

PS : I work with Symfony 2.2... it looks like a solution had been found and delivered with this version but the problem remains

Upvotes: 0

Views: 2763

Answers (1)

Damien
Damien

Reputation: 5882

By default, each Symfony2 form type have the required option set to true, no matter what you have in your validation Assert.

http://symfony.com/doc/master/book/forms.html#field-type-options

The required option is only a "nice to have" feature and does not do true server-side validation. This is the role of your validation Assert.

Just put required=false on your description:

$builder->add('description', 
              'textarea', array(
                 'label' => $this->translator->trans('product.demo.description'),
                 'required' => false
              ));

Upvotes: 4

Related Questions