2016-02-16 20 views
5

Tak ... Chcę wyłączyć wejście w Symfony 3.0.2 w zależności od instrukcji IF w moim kontrolerze. Jak mogę to zrobić? Ustawienie wartości na przykład pola first_namesymfony 3 jak wyłączyć wejście w kontrolerze

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

Więc pomyślałem o czymś takim -> setOption („wyłączone”, true)

Odpowiedz

4

Korzystanie z opcji formularza, jak sugerujesz, można określić typ formularz z czymś jak:

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

a następnie w kontrolerze utworzyć formularz z:

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

Ale jeśli wartość wyłączona zależy od wartości w jednostce, powinieneś raczej użyć 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))); 
    }); 
}