Symfony 3 how to disable input in the controller

So ... I want to disable input in Symfony 3.0.2 depending on the IF statement in my controller. How can I do it? Parameter value, for example, field first_name

$form->get('firstname')->setData($fbConnect['data']['first_name']); 

So, I thought of something like -> setOption ('disabled', true)

+5
source share
1 answer

Using form parameters, as you suggest, you can define your type of form 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 a form with:

 $form=$this->createForm(MyType::class, $yourEntity, array('first_name_disabled'=>$disableFirstNameField)); 

But if the value is disabled, it depends on the value in the entity, you should rather use 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))); }); } 
+4
source

Source: https://habr.com/ru/post/1243128/


All Articles