Question

I'm making a clone action in sonata admin--following the recommendations of 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'));
}
}

after setting an id on the $clonedobject I get a DBAL exception. primary keys with same id not allowed--

I've tried setting a unique id

no id with the hope that auto increment in my schema would force ++

thanks for your help

Was it helpful?

Solution 2

I think the easy solution is to set your id to null and doctrine will generate an id for you while creating the cloned object...

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

OTHER TIPS

Geert is right, setting the id to null is the way to go with Doctrine.

However, rather than having to implement a setId method in your object, you may as well override the __clone method as follows:

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

See How to re-save the entity as another row in Doctrine 2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top