Alex Alex - 3 months ago 20
Twig Question

Symfony2 form type entity: Option is not selected

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

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


Class FacilityTypeType:

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


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

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


The RoomFacility entity has a ManToOne relation to entity FacilityType.

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


Any suggestions?

Thanks in advance

Alex

Answer

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