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?
2 Answers
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.
4 Comments
$event->getForm() or $event->getData(). Then you will be able to perform any logic you need.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)));