There are two entities, Category and Device. A device can be related to exactly one category. A category can be related to many devices.
I use following custom form type to create and edit a device:
class DeviceFormType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options) {
$builder->add('name');
$builder->add('category', 'entity', array(
'class' => 'MySupportBundle:Category',
'property' => 'name'
));
}
public function getName() {
return 'device';
}
public function getDefaultOptions(array $options) {
return array(
'data_class' => 'My\SupportBundle\Entity\Device',
);
}
}
So basically each device has a name and is assign to one category. This works fine. Now when I try to edit the device and change the category, in the choice list the current category is not selected:
public function editDeviceAction($id, Request $request) {
$em = $this->getDoctrine()->getEntityManager();
$device = $em->getRepository('MySupportBundle:Device')->find($id);
$form = $this->createForm(new DeviceFormType(), $device);
$valid = false;
if ('POST' == $request->getMethod()) {
$form->bindRequest($request);
if ($form->isValid()) {
$device = $form->getData();
$device->setUpdatedAt(new \DateTime('now'));
$em->flush();
return $this->redirect($this->generateUrl('view_shop'));
} else {
$valid = true;
}
} else {
$valid = true;
}
return $this->render('MySupportBundle:Shop:editDevice.html.twig', array(
'form' => $form->createView(),
'valid' => $valid,
'device' => $device
));
}
Any ideas how to set the category as selected?
Device:
<entity name="My\SupportBundle\Entity\Device" table="device">
<id name="id" type="integer" column="id">
<generator strategy="AUTO" />
</id>
<many-to-one field="category" target-entity="Category"/>
<field name="name" column="name" type="string" length="255"/>
</entity>
Category:
<entity name="My\SupportBundle\Entity\Category" table="category">
<id name="id" type="integer" column="id">
<generator strategy="AUTO" />
</id>
<one-to-many field="device" target-entity="Device" mapped-by="Device"/>
<field name="name" column="name" type="string" length="255"/>
</entity>
Finally I found a solution by myself.
Obviously when creating form view like this
and in form type like this
it won’t work. Because “type” is wrong. It has to be “category” instead of “type”. Very strange but this was the problem 😉