Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormType : required attribute doesn't work with Entity Type

I'm working with Symfony 3.4, and when trying to add required HTML5 attribute to my "fournisseur" Field, I didn't get it in HTML.

ArrivageType.php:

$builder
->add('fournisseur', EntityType::class, array(
    'class' => 'AppBundle:Fournisseur',
    'choice_label' => 'name',
    //'empty_data'  => null,
    'required' => true,
))
like image 598
Med Karim Garali Avatar asked Nov 01 '25 02:11

Med Karim Garali


1 Answers

You have multiple and expanded not set, these options are by default false, meaning you are trying to render a select element.

By default Symfony doesn't add a required attribute to select elements when required option is set to true, instead it doesn't render an empty option in your select element.

If you want to have an empty option and required attribute added to your select element you should add a placeholder option in your form:

$builder
    ->add('fournisseur', EntityType::class, array(
        'class' => 'AppBundle:Fournisseur',
        'choice_label' => 'name',
        //'empty_data'  => null,
       'required' => true,  // not needed since it is true by default,
       'placeholder' => 'Choose a fournisseur'
    ))

This will render an empty option with 'Choose a fournisseur' text inside your select element, along with required attribute to this select.

like image 183
iiirxs Avatar answered Nov 04 '25 04:11

iiirxs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!