有两个实体,Category和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',
);
}
}
所以基本上每个设备都有一个名称并分配给一个类别。这工作正常。现在,当我尝试编辑设备并更改类别时,在选择列表中未选择当前类别:
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
));
}
任何想法如何将类别设置为选中?
设备:
<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>
类别:
<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>