1

I want to create a duplicate product using the product id programmatically. I have tried many solutions but have not had success. How to do it?

asked Aug 3, 2023 at 12:54

2 Answers 2

0

Let's create a class that would handle this:

namespace .....
class ProductClone
{
 private \Magento\Catalog\Model\Product\Copier $copier;
 private \Magento\Catalog\Api\ProductRepositoryInterface $repository;
 public function __construct(
 \Magento\Catalog\Model\Product\Copier $copier,
 \Magento\Catalog\Api\ProductRepositoryInterface $repository
 ) {
 $this->copier = $copier;
 $this->repository = $repository;
 }
 public function duplicate(int $productId): \Magento\Catalog\Api\Data\ProductInterface
 {
 $product = $this->repository->getById($productId);
 return $this->copier->copy($product);
 }
}

Now you just need to include this class as a dependency in your custom logic and call the duplicate method with your product id as a parameter.

Watch out for typos in the code above, I didn't test it.

answered Aug 3, 2023 at 13:47
0

Copying products programmatically in Magento 2 can be achieved using the native approach, which utilizes Magento's built-in functionality in the Admin panel for copying products. To do this, you can take advantage of the Magento\Catalog\Controller\Adminhtml\Product\Duplicate controller along with the Magento\Catalog\Model\Product\ProductCopier class, which simplifies the process for you.

Below is an example of how you can implement the product duplication:

/** @var \Magento\Catalog\Model\Product\Copier $productCopier */
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$product = $productRepository->get('SKU');
$duplicatedProduct = $productCopier->copy($product);

In the code above, we use the ProductRepositoryInterface to load the product with the specified SKU you want to duplicate. Then, we pass that product instance to the ProductCopier to create a new duplicated product.

answered Aug 3, 2023 at 13:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.