Symfony2表单类型实体

Symfony2表单类型实体

本文介绍了Symfony2表单类型实体:未选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Symfony2(2.3)实体表单类型从Doctrine实体加载HTML选择的选项:

I use a Symfony2 (2.3) entity form type to load the options of a HTML select from a Doctrine entity:

Class RoomFacilityType:

Class RoomFacilityType:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('title', 'text', array('label' => 'Bezeichnung', 'required' => false))
            ->add('save', 'submit', array('label' => 'Speichern'));

    // add referenced object facility type
    $builder->add('facilityType', new FacilityTypeType());
}

类FacilityTypeType:

Class FacilityTypeType:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('type', 'entity', array('label' => 'Ausstattung', 'class' => 'xyz\abcBundle\Entity\FacilityType', 'property' => 'type'));
}

在控制器中,我创建一个带有RoomFacility实体的表单:

In the controller I create a form with a RoomFacility entity:

$formRoomFacility = $this->createForm(new RoomFacilityType(), $roomFacility);

RoomFacility实体与实体FacilityType有ManToOne关系。

The RoomFacility entity has a ManToOne relation to entity FacilityType.

当表单由树枝模板呈现时,不会选择HTML选择的选项(但是当我使用文本形式类型时,将显示正确的值ist):

When the form is rendered by a twig template, no option of the HTML select is selected (but when I use a text form type instead, the correct value ist displayed):

{{ form_widget(formRoomFacility.facilityType.type) }}

我已经发现有关如何通过明确设置其值来设置选项的问题,但这并不能解决我的问题:

I have found questions about how to set an option selected by setting it's value explicitly, but that doesn't solve my problem either:

$formRoomFacility->get('facilityType')->setData($roomFacility->getFacilityType());

任何建议?

提前感谢

Alex

推荐答案

也许以下将会做你想要的:

Perhaps the following will do what you want:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('title', 'text', array('label' => 'Bezeichnung', 'required' => false))
            ->add('type', 'entity', array('label' => 'Ausstattung', 'class' => 'xyz\abcBundle\Entity\FacilityType', 'property' => 'type'))
            ->add('save', 'submit', array('label' => 'Speichern'))
    ;
}

这篇关于Symfony2表单类型实体:未选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 16:46