Reputation: 131
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)
Upvotes: 8
Views: 4477
Reputation: 864
I use below code to change my form without use FormEvents
.
After building $form
just get all configs and do changes, remove the field and re-creating using new $attrs
NOTE: I'm using Symfony 4
$form = $this->createForm(YourEntityFormType::class, $yourEntity);
// Change one or more fields through certain condition
if (true === SOME_CONDITION) {
$field = $form->get('your_field');
$attrs = $field->getConfig()->getOptions();
$attrs['attr']['readonly'] ='readonly';
$attrs['disabled'] ='disabled';
$form->remove($field->getName());
$form->add($field->getName(),
get_class($field->getConfig()->getType()->getInnerType()),
$attrs);
}
Remember to do it before call $form->handleRequest()
Upvotes: 1
Reputation: 3135
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)));
});
}
Upvotes: 9