Cannot update a duplicate product


#1

hy , when I duplicate a product, I can not edit anymore
there is my code :

  $factory = $this->container->get('sylius.factory.product');
    $manager = $this->container->get('sylius.manager.product'); // Alias for appropriate doctrine manager service.
    $defaultVariantResolver = $this->container->get('sylius.product_variant_resolver.default');

    $newresource = new \stdClass();
    $newresource->code = $ref;
    $newresource->name = $resource->getName();
    $newresource->description = $resource->getDescription();
    $newresource->shortDescription = $resource->getShortDescription();
    $newresource->metaKeywords = $resource->getMetaKeywords();
    $newresource->metaDescription = $resource->getMetaDescription();
    $newresource->mainTaxon = $resource->getMainTaxon();

    $product = $factory->createWithVariant();

    $product->setCode($newresource->code);
    $product->setName($newresource->name);
    $product->setDescription($newresource->description);
    $product->setSlug(uniqid());
    $product->setShortDescription($newresource->shortDescription);
    $product->setMetaKeywords($newresource->metaKeywords);
    $product->setMetaDescription($newresource->metaDescription);
    $product->setMainTaxon($newresource->mainTaxon);


    $productVariant = $defaultVariantResolver->getVariant($product);
    $productVariant->setCode($newresource->code);
    $productVariant->setName($newresource->name);


    $manager->persist($product);
    $manager->flush();

the error i get :
OptimisticLockException RaceConditionException
HTTP 500 Internal Server Error
Operated entity was previously modified.

ResourceUpdateHandler->handle(object(Product), object(RequestConfiguration), object(EntityManager_9a5be93))
in src/AppBundle/Controller/ProductController.php (line 94)
return $event->getResponse(); } return $this->redirectHandler->redirectToResource($configuration, $resource); } try { $this->resourceUpdateHandler->handle($resource, $configuration, $this->manager); } catch (UpdateHandlingException $exception) { if (!$configuration->isHtmlRequest()) { return $this->viewHandler->handle( $configuration, View::create($form, $exception->getApiResponseCode()) );


#2

Use PHP clone method instead - http://php.net/manual/en/language.oop5.cloning.php.

You can clone the object, set its code and id to null. I believe this’d be more clean solution.


#3

The cloning method worked for me as well, just keep in mind of the Images\ Entries you will have to duplicate the image and assign it a new ID, so its best to create a new Image entry and populate it with the original products values