1

There is an issue with Magento 2.2.2 (and possibly previous versions) where products that have a url_path set on them cannot be duplicated - "The value specified in the URL Key field would generate a URL that already exists." For us these came from migrated products, but this is just background for my current problem.

To get around the issue, I added an afterCopy plugin to clear url_path from the duplicated product. However, it would not fire, and after debugging I decided to just add a beforeCopy to clear it from the product prior to copying. This resulted in both before and after methods running. Some more experimentation and without the $product->setUrlPath(null); call it will not run the afterCopy method.

<?php

namespace My\Namespace\Model\Plugin;

class CopierPlugin
{
    public function afterCopy(\Magento\Catalog\Model\Product\Copier $subject, $duplicate)
    {
        $duplicate->setUrlPath(null);
        return $duplicate;
    }

    public function beforeCopy(\Magento\Catalog\Model\Product\Copier $subject, \Magento\Catalog\Model\Product $product)
    {
        $product->setUrlPath(null); // without this line, the afterCopy will not fire
        return [$product];
    }
}

Has anyone else seem similar behavior with plugins? I don't have time to delve further into the depths of how Magento determines to run specific plugin methods at the moment, but if I get some more time I may dig in further.

0

If you take a look at the class \Magento\Catalog\Model\Product\Copier the method copy is trying to save the save the duplicated item $duplicate->save() some exception is being thrown somewhere and the processes is not being completed, that's why afterCopy is never being called.

  • That makes perfect sense, could have sworn I looked through the copy method for that exact reason. Must have been too close to it, thanks! – jay Feb 20 '18 at 23:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.