symfony 3如何在控制器中禁用输入

时间:2016-02-16 11:29:13

标签: php symfony input

所以...我想根据控制器中的IF语句禁用Symfony 3.0.2中的输入。我怎么做?设置示例字段first_name的值

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

所以我想到了类似的事情 - > setOption('disabled',true)

1 个答案:

答案 0 :(得分:5)

使用表单选项,就像您建议的那样,您可以使用以下内容定义表单类型:

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

然后在您的控制器中创建表单:

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

但是如果disabled的值取决于实体中的值,则应该使用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)));
    });
}