在sonata admin自定义克隆操作中强制自动增加id

时间:2014-05-01 19:46:31

标签: mysql symfony doctrine-orm sonata-admin symfony-sonata

我正在sonata管理员中进行克隆操作 - 遵循Sonata docs的建议:

<?php // src/Acme/DemoBundle/Controller/CRUDController.php

namespace Acme\DemoBundle\Controller;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CRUDController extends Controller
{
public function cloneAction()
{
    $id = $this->get('request')->get($this->admin->getIdParameter());

    $object = $this->admin->getObject($id);

    if (!$object) {
        throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
    }

    $clonedObject = clone $object;
    $clonedObject->setName($object->getName()." (Clone)");

    $this->admin->create($clonedObject);

    $this->addFlash('sonata_flash_success', 'Cloned successfully');

    return new RedirectResponse($this->admin->generateUrl('list'));
}
}

在$ clonedobject上设置id后,我得到一个DBAL异常。不允许具有相同ID的主键 -

我已尝试设置唯一ID

没有id,希望我的架构中的自动增量会强制++

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

Geert是对的,将id设置为null是与Doctrine一起使用的方式。

但是,您不必在对象中实现setId方法,也可以覆盖__clone方法,如下所示:

public function __clone()
{
    parent::__clone();
    $this->id = null;
    $this->name .= " (Clone)";
}

请参阅How to re-save the entity as another row in Doctrine 2

答案 1 :(得分:1)

我认为简单的解决方案是将您的ID设置为 null ,并且doctrine会在创建克隆对象时为您生成ID ...

$clonedObject = clone $object;
$clonedObject->setId(NULL);
$clonedObject->setName($object->getName()." (Clone)");