简体   繁体   English

Symfony3:构造FormType

[英]Symfony3: Construct FormType

I have a form in Symfony3, which I initialize - following the docs - as followed: 我在Symfony3中有一个表单,我按照文档进行了初始化-如下所示:

$form=$this->createForm(BookingType::class,$booking);

$booking is an already existing entity, which I want to modify - but I want to modify the form depending on the entity - like: $ booking是一个已经存在的实体,我想对其进行修改-但我想根据该实体来修改表单-例如:

public function buildForm(FormBuilderInterface $builder,$options) {
    $builder->add('name');
    if(!$this->booking->getLocation()) {
        $builder->add('location');
    }
}

Prior Symfony 2.8 it was possible to construct the FormType like: 在先前的Symfony 2.8中,可以像这样构造FormType:

$form=$this->createForm(new BookingType($booking),$booking);

Which is exactly what I want :) But in Symfony3 this method throws an exception. 这正是我想要的:)但是在Symfony3中,此方法引发异常。 How can I pass an entity to my formtype? 如何将实体传递给表单类型?

You can also change a form type based on custom options. 您还可以基于自定义选项更改表单类型。

In the form type: 在表单中输入:

public function buildForm(FormBuilderInterface $builder, $options) {
    $builder->add('name');

    if($options['localizable']) {
        $builder->add('location');
    }
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'localizable' => true,
    ));
}

In the controller: 在控制器中:

$form = $this->createForm(BookingType::class, $booking, array(
    'localizable' => !$booking->getLocation(),
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM