检索链接到Symfony 2中表单的上一个对象

时间:2016-12-07 21:03:51

标签: forms symfony

我有一个表单来编辑用户的地址(我将实体地址传递给表单)。当我修改地址并提交表单时,我想停用(使用setActive函数)我传递的实体(没有新值)并使用新值创建一个新行。有可能吗?

示例:

$em = $this->getDoctrine()->getManager();
$client_adr = $em->getRepository('EcommerceBundle:ClientAdresse')->find($id_adr); // here it's the entity that i want disable

$form = $this->createFormBuilder($client_adr)
        ->add('prenom', TextType::class)
        ->add('nom', TextType::class)
        ->add('adresse', TextType::class)
        ->add('lieu_dit', TextType::class)
        ->add('complement', TextType::class)
        ->add('code_porte', TextType::class)
        ->add('cp', TextType::class)
        ->add('pays', TextType::class)
        ->add('save', SubmitType::class, array('label' => 'Modifier'))
        ->getForm();

$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$adr = $form->getData(); // here it's the entity with new values
$em->persist($new_adr);

$em->flush();
}

在这个例子中,如果我修改我的实体的名称,我想要我的对象" $ client_adr"保留其先前的值并被禁用(如果我通过示例调用setActive)并且我希望我的对象$ new_adr保存在具有修改值的数据库中的新行上。

由于

1 个答案:

答案 0 :(得分:0)

简单。在找到您的对象之后但在设置表单之前,clone您的对象然后设置id null。您可能必须在实体类中添加setId方法。

$client_adr = $em->getRepository('EcommerceBundle:ClientAdresse')->find($id_adr);
$clone_adr = clone $client_adr;
$clone_adr->setId(null);
$client_adr->setIsActive(false);

$form = $this->createFormBuilder($clone_adr) ...

....

$em->persist($client_adr); // save old, inactive
$em->persist($new_adr); // save new.

$em->flush();