Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Last active January 13, 2016 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdevilopers/5306ee3417791227abf3 to your computer and use it in GitHub Desktop.
Save webdevilopers/5306ee3417791227abf3 to your computer and use it in GitHub Desktop.
Dynamically set field type option readonly to false on choice if dependent radio button is checked true using symfony2
<?php
use Symfony\Component\Form\AbstractType;
class FooBarType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('addFoo', 'choice', array(
'choices' => array(
'0' => 'No',
'1' => 'Yes'
),
'expanded' => true,
'required' => true
))
->add('selectFoo', 'entity', array(
'class' => 'Acme\AppBundle\Entity\Foo',
'attr' => array('readonly' => true)
))
;
$builder->addEventListener(
FormEvents::SUBMIT,
function(FormEvent $event) use ($options) {
$data = $event->getData();
$form = $event->getForm();
$disabled = $data->getFoo() == '1' ? false : true;
$form->add('selectFoo', 'entity', array(
'class' => 'Acme\AppBundle\Entity\Foo',
'attr' => array('readonly' => $readonly)
));
}
);
}
}
@webdevilopers
Copy link
Author

See: http://symfony.com/doc/current/reference/forms/types/text.html#read-only

Issue:
symfony/symfony#12946

For an easier implementation cross fingers for the field dependent support: symfony/symfony#5807

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment