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!

  • beforeSave method comes from where ? Is it of the modal class of product ? – Avesh Naik Aug 31 '18 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 Aug 31 '18 at 14:11
  • include this code in your question. – Avesh Naik Aug 31 '18 at 14:59
  • Already included – Mr. Nanhe Aug 31 '18 at 15:37
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.

  • Thanks for your help but it does not work. – Mr. Nanhe Sep 1 '18 at 15:03
  • what's the error ? – Avesh Naik Sep 2 '18 at 16:06
  • Page loading continuously and showing error "This page isn’t working" – Mr. Nanhe Sep 4 '18 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 Sep 4 '18 at 11:00
  • I modified my ans please check – Avesh Naik Sep 4 '18 at 11:12

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.