[英]Symfony2 entity choice list set selected object
有兩個實體, 分類和設備 。 設備可以與一個類別相關。 類別可以與許多設備相關。
我使用以下自定義表單類型來創建和編輯設備:
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>
嗨,我不確定,但是你在檢查一對多和多對一的關系嗎?它們是單向的還是雙向的?你可以告訴我們你的設備和類別實體類......
您正在使用名為find()
的自定義存儲庫方法 - 根據您重載的方式,可能尚未獲取Category
。 您可以依賴於默認的findOneById(int $id)
方法。
最后我自己找到了解決方案。
顯然在創建這樣的表單視圖時
{{ form_widget(form.type)}}
並且像這樣的表單類型
$builder->add('type', 'entity', array(
'class' => 'MyBundle:Category',
'property' => 'name'
));
它不會起作用。 因為“類型”是錯誤的。 它必須是“類別”而不是“類型”。 很奇怪,但這是問題;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.