0

I am trying to remove/unset all categories from a product using below code. It's working with Magento 2.1 but not with Magento 2.2.

How can we do this?

app/code/Vender/Module/etc/di.xml

<plugin name="Vender-Module-product-model" type="Vender\Module\Plugin\TestPlugin" sortOrder="1" />

app/code/Vender/Module/Plugin/TestPlugin.php

namespace Vender\Module\Plugin;

class TestPlugin    
{ 
    public function beforeSave(\Magento\Catalog\Model\Product $product)   
    {
        $product->setCategoryIds("1");
    }

}

Any help would be appreciated!

4
  • beforeSave method comes from where ? Is it of the modal class of product ?
    – Avesh Naik
    Commented Aug 31, 2018 at 13:56
  • I have created a plugin for this. app/code/Vender/Module/etc/di.xmldi.xml <type name="Magento\Catalog\Model\Product"> <plugin name="Vender-Module-product-model" type="Vender\Module\Plugin\TestPlugin" sortOrder="1" /> </type> app/code/Vender/Module/Plugin/TestPlugin.php class TestPlugin { public function beforeSave(\Magento\Catalog\Model\Product $product) { $product->setCategoryIds("1"); } }
    – Mr. Nanhe
    Commented Aug 31, 2018 at 14:11
  • include this code in your question.
    – Avesh Naik
    Commented Aug 31, 2018 at 14:59
  • Already included
    – Mr. Nanhe
    Commented Aug 31, 2018 at 15:37

1 Answer 1

0

If it was working fine with 2.1 and not working on 2.2. I suggest you to using factory class of product class.

public function beforeSave(\Magento\Catalog\Model\ProductFactory $product)
{
  $prod = $product->create()->load(<product id>);
  $prod->setCategoryIds("1");  
 // $prod->save();
  $prod->getResource()->save();      
} 

It is recommended to use factory class.

8
  • Thanks for your help but it does not work.
    – Mr. Nanhe
    Commented Sep 1, 2018 at 15:03
  • what's the error ?
    – Avesh Naik
    Commented Sep 2, 2018 at 16:06
  • Page loading continuously and showing error "This page isn’t working"
    – Mr. Nanhe
    Commented Sep 4, 2018 at 8:21
  • ohhhhh ok i faced this kind of problem. See your method it's beforeSave. When you enter this method and call save method, then it will call again beforeSave method. It's like recursion
    – Avesh Naik
    Commented Sep 4, 2018 at 11:00
  • I modified my ans please check
    – Avesh Naik
    Commented Sep 4, 2018 at 11:12

Your Answer

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

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