カテゴリとデバイスの2つのエンティティがあります。デバイスは、1つのカテゴリにのみ関連付けることができます。カテゴリは多くのデバイスに関連付けることができます。
次のカスタムフォームタイプを使用して、デバイスを作成および編集します。
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',
);
}
}
したがって、基本的に各デバイスには名前があり、1つのカテゴリに割り当てられます。これは正常に機能します。デバイスを編集してカテゴリを変更しようとすると、選択リストで現在のカテゴリが選択されません。
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>