symfony 3 how to disable input in controller symfony 3 how to disable input in controller symfony symfony

symfony 3 how to disable input in controller


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)));    });}


Another way to change Symfony Form field in a Controller

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 conditionif (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()