1

I have a task to make some of the checkboxes in a form choice field disabled, and some not. Is there an easy way to achieve that without rewriting choice field layouts?

James Dunn
  • 8,064
  • 13
  • 53
  • 87
mrMantir
  • 2,285
  • 1
  • 17
  • 20
  • Check my answer here, it's a quick and effective solution http://stackoverflow.com/questions/31535943/symfony-choice-type-with-disabled-options/34526846#34526846 – Jacer Omri Dec 30 '15 at 09:44

2 Answers2

3

You can set on your choice field the disabled state :

$builder->add('myChoice', 'choice', array('attr'=>array('disabled'=>'disabled')));

Or you could use an EventSubscriber to listen on PostSetData event if you have some logic needed to set the disabled state. Check cookbook dynamic form generation for implementation details.

Flavien
  • 94
  • 6
  • Hi Flaveien, thanks for answer. I cant use first, simplest option because i have about 7 choice fields and 4 of them must have readonly state. I think second suggestion can do the job. Can i calculate with EventSubscriber value from many fields? I think about making two subfields of type choice - one readonly and second without that flag and calculate value from them. – mrMantir Oct 01 '12 at 08:08
  • Yes you can do that. The event object will receive current form and data that you can access with `$event->getForm()` or `$event->getData()`. Then you will be able to perform any logic you need. – Flavien Oct 01 '12 at 09:17
  • ok i tried that and works almost perfect. One think i cant understand its passing to my DataTransformer::reverseTransform names of my subfields instead of calculated value. Can you help me with that situation? – mrMantir Oct 01 '12 at 09:24
  • dont know how yet but it starts to work properly even without subscriber for binding data. Thank you very much for help :) – mrMantir Oct 01 '12 at 11:02
2

I want to clarify something about the solution of Flavien, but I don't have sufficient reputation to comment under his post.

$builder->add('myChoice', 'choice', array('attr'=>array('disabled'=>'disabled')));

The use of 'disabled'=>'disabled' is wrong (because the right part is wrong). It works but disabled (left) accepts boolean and should receive true or false. In this case it really works because simply anything but 0 is true.

Why am I explaining this? Because maybe someone wants to use the same form in different places and just disable one input (in practice making it readonly). So he will feed a variable to the 'disabled' parameter and if that variable is not boolean it will always result in disabling the input.

tl;dr

 $builder->add('myChoice', 'choice', array('attr'=>array('disabled'=>true)));

or

$builder->add('myChoice', 'choice', array('attr'=>array('disabled'=>false)));
Bojidar Stanchev
  • 468
  • 5
  • 20