从Symfony2中的表单获取数据后克隆对象 [英] Cloning object after getting data from a form in Symfony2
问题描述
我确定我在这里缺少一些非常基本的东西。
I'm sure I'm missing something very basic here.
我有一个表单,当用户更新表单的字段时,我不想要更新底层的实体,但是想要创建一个新的实体与新的值。
I have a form, and when the user updates the fields of the form I don't want to update the underlying entity but want to create a new entity with the new values.
要克隆Doctrine实体,我遵循指示here 。
To clone Doctrine entities I followed the indication here.
所以我的代码是(我们想要克隆id = 3的对象:
So my code is (let's say I want to clone the object with id=3:
$id = 3;
$storedBI = $this->getDoctrine()
->getRepository('AppBundle:BenefitItem')
->find($id);
$form = $this->createForm(new BenefitItemFormType(), $storedBI);
$form->handleRequest($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$newBI = clone $form->getData();
$em->persist($newBI);
$em->flush();
}
它根本不起作用,它正确地创建了一个新对象,新的数据从表单传递(这是可以的),但也是使用相同的新数据更新旧存储对象。
It simply does not work. It properly creates a new object with the new data passed from the form (which is ok), but also updates the "old" stored object with the same new data.
任何想法?
推荐答案
你必须克隆你的对象d创建表单:
You have to clone your object during the form creation:
$ form = $ this-> createForm(new BenefitItemFormType(),clone $ storedBI);
如果这不起作用,首先尝试分离您的克隆对象。
If this does not work, try to detach
your cloned object first.
这篇关于从Symfony2中的表单获取数据后克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!