Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony 3 how to disable input in controller

Tags:

php

input

symfony

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)

like image 687
Denis Wróbel Avatar asked Feb 16 '16 11:02

Denis Wróbel


1 Answers

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)));
    });
}
like image 121
Alsatian Avatar answered Oct 19 '22 11:10

Alsatian