Search code examples
phpjqueryformstwitter-bootstrapsymfony

symfony2 + bootstrap 3 readonly select dropdown still editable


I am using symfony2 and bootstrap 3 and when I set the readonly attribute to a form field, it gets greyed and I have the forbidden cursor but the field is still editable (in my case a select dropdown).

The readonly attribute would work great for a simple text field, but not for a select.

How can I make sure users can't click a select and change its value ?

I can't use "disabled" as I need the value to be passed to the form. Using jquery to rewrite the readonly attribute also did not work.

my form:

            ->add('product', 'entity', array(
                    'label' => 'Produit',
                    'class' => 'AppBundle:MarketPlace\Product',
                    'read_only' => true,
                ))

Solution

  • Create a data transformer ProductToTextTransformer for your entity as explained in the doc, and then use it in your formbuilder, adding a select or a readonly text according to the condition for the select to be disabled or not :

         //...
    
         // this assumes that the entity manager was passed in as an option
         $entityManager = $options['em'];
         $transformer = new ProductToTextTransformer($entityManager);
         if ($condition_to_disabled_the_select){
           $builder->add('product', 'entity', array(
                    'label' => 'Produit',
                    'class' => 'AppBundle:MarketPlace\Product',
                ));
         }
         else{
            $builder->add(
                $builder->create('product', 'text', array('label' => 'Produit', 'read_only' => true))
                        ->addModelTransformer($transformer)
            );
         }