So... I want to disable an input in Symfony 3.0.2 depending on IF statement in my controller. How do I do that? Setting value for example field first_name
$form->get('firstname')->setData($fbConnect['data']['first_name']);
So I thought about something like ->setOption('disabled', true)
Using the form options, like you suggest, you can define your form type with something like :
class FormType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('first_name',TextType::class,array('disabled'=>$option['first_name_disabled']));
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array('first_name_disabled'=>false));
}
}
And then in your controller create the form with :
$form=$this->createForm(MyType::class, $yourEntity, array('first_name_disabled'=>$disableFirstNameField));
But if the value of disabled depends on the value in the entity, you should rather use a formevent :
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('first_name',TextType::class);
// Here an example with PreSetData event which disables the field if the value is not null :
$builder->addEventListener(FormEvents::PRE_SET_DATA,function(FormEvent $event){
$lastName = $event->getData()->getLastName();
$event->getForm()->add('first_name',TextType::class,array('disabled'=>($lastName !== null)));
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With