我有一个实体的创建表单,它按照预期的方式工作 . 此表单的实体与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;
}
1 回答
editPostAction缺少以下内容:
它现在有效 . 我希望将来可以帮助别人错过这些电话中的一个或两个 .