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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
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?
dont know how yet but it starts to work properly even without subscriber for binding data. Thank you very much for help :)
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)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.