我有一个实体的创建表单,它按照预期的方式工作。这个表单的实体与另一个实体关联ManyToMany,而另一个则用于填充多选字段。
当我保存创建表单并从多选字段中选择多个选项时,表单类型的实体和相关实体之间的关联将正确保存。
然而,我也有一个编辑表单,它使用相同的表单类型类和模板。当我加载编辑表单并将现有实体的信息自动填充到其中时,我发现与多选字段实体的关系确实得到了反映;选择多选框的适当字段。
当我去保存编辑表单时,就是出现问题的时候。如果我取消多选字段中的选项,我希望在保存编辑表单时,这些选项将被取消关联,但事实并非如此。相反,原始关系将被保留,就好像没有更改任何选项一样。
我还需要做什么,以便在取消多选中的选项时,这些选项将解除关联?非常感谢。
在实体中:
/**
* unidirectional ManyToMany
* @ORM'ManyToMany(targetEntity="'Myco'ClientBundle'Entity'Country", cascade={"persist"}, orphanRemoval=true)
* @ORM'JoinTable(name="offer_country",
* joinColumns={@ORM'JoinColumn(name="offer_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM'JoinColumn(name="country_id", referencedColumnName="id")}
* )
* */
private $countries;
/**
* This is method getCountries
*
* @return ArrayCollection
*
*/
public function getCountries()
{
return $this->countries;
}
在表单类型中,以下是如何创建多选框:
->add('countries', 'entity', [
'class' => 'ClientBundle:Country',
'property' => 'name',
'required' => false,
'expanded' => false,
'multiple' => true,
'mapped' => true
])
在控制器中,以下是与编辑有关的功能:
/**
* Displays edit form
*
* @throws NotFoundHttpException
*
* @param Request $request
* @param int $id
*/
public function editAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$offer = $em->getRepository('ClientBundle:Offer')->find($id);
if (!$offer)
{
throw new NotFoundHttpException('Offer not found!');
}
$this->setEditForm($offer, '/offer/editPost/' . $id);
return [
'form' => $this->form->createView(),
'devicesForm' => $this->getDevicesForm('/devices/listJson')->createView(),
'gate' => $this->gate
];
}
/**
* Handles submission of edit form
*/
public function editPostAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$offer = $em->getRepository('ClientBundle:Offer')->find($id);
if (!$offer)
{
throw new NotFoundHttpException('Offer not found!');
}
$this->setEditForm($offer);
$this->form->handleRequest($request);
if (!$this->form->isValid())
{
throw new InvalidArgumentException('Unable to save this item due to invalid argument(s).');
}
return ['form' => $this->form->createView()];
}
/**
* Sets up $this->form as a new edit form with the specified Offer
*
* @param Offer $offer
*/
protected function setEditForm($offer, $action = '')
{
$this->setOffer($offer);
$this->form = $this->createForm(new OfferType, $this->offer, ['action' => $action]);
$this->form->add('submit', 'submit');
}
/**
* Sets $this->offer
* @param Offer $offer
*/
protected function setOffer(Offer $offer = null)
{
if (!$offer)
{
$offer = new Offer;
}
$this->offer = $offer;
}
editPostAction缺少以下内容:
$em->persist($this->offer);
$em->flush();
它现在起作用了。我希望这能帮助其他人在未来错过其中一个或两个电话。