1

I'm trying to add a product automatically to a category when custom attribute "new" is set and remove it when it is unset. I tried to do this via plugin aroundSave

but I'm only getting same values for "new" before and after the proceed() call:

class UpdateAttributes
{
    protected $logger;
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
    protected $_productCollectionFactory;

/**
 * @param \Magento\Catalog\Model\Product $subject
 * @param callable $proceed
 * @return |null
 */
public function aroundSave(\Magento\Catalog\Model\Product $subject, callable $proceed)
{


    $beforeValue = $subject->getData('new');

    $this->logger->debug('BEFOOOOOOOOOOOORE :' );
    $this->logger->debug($beforeValue);
    $result = null;


    if($beforeValue){
        $result = $proceed();
    }



    $this->logger->debug('AAAAAAAAAAAAAAAFTER :' );
    $afterValue = $subject->getData('new');
    $this->logger->debug($afterValue);


    if ($result) {

        $this->_processData($beforeValue, $afterValue, $subject);
    }

    return $result;

}

protected function _processData($before, $after, $product){
    if($before != $after){
        $this->logger->debug('-----------NOT THE SAME -----------' );
        if($after == 1){
            $this->logger->debug('-----------ADD -----------' );
            $this->_addOrRemoveFromCategory($product, ['41']);
        }
        else{
            $this->logger->debug('-----------REMOVE -----------' );
            $this->_addOrRemoveFromCategory($product, ['41'], false);
        }
    }

}
protected function _addOrRemoveFromCategory($product, $categorieIds, $add = true){
    $toAddCategoryId = $categorieIds;

    $currentCatIds = $product->getCategoryIds();
    if($add){
        $newCategoryIds = array_unique(
            array_merge(
                $currentCatIds,
                $toAddCategoryId
            )
        );
    }
    else{
        $newCategoryIds = $currentCatIds;
        foreach ($categorieIds as $id){
            $index = array_search($id, $currentCatIds);
            unset($newCategoryIds[$index]);
        }
    }

    $product->setCategoryIds($newCategoryIds);
}


}

Should I use another method or use an observer?

I'm pretty new to Magento and can't find proper literature.

2 Answers 2

1

Try it with Observer.

Use event catalog_product_save_after

Put this events.xml in below path

app\code\YOUR_NAMESPACE\YOURMODULE\etc\adminhtml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_after">
        <observer name="test_name" instance="YOUR_NAMESPACE\YOUR_MODULENAME\Observer\Productsaveafter" />
    </event>
</config>

And put your Productsaveafter.php in below path

app\code\YOUR_NAMESPACE\YOURMODULE\Observer\

<?php

namespace YOURNAMESPACE\YOURMODULENAME\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct();  // you will get product object
        $_sku=$_product->getSku(); // for sku

        // Do your Logic

        // Check OLD value for attribute 'new'
        $oldValue = $product->getOrigData('new');

        // New value for attribute 'new'
        $newValue = $product->getData('new');
    }   
}

Let me know if this works for you.

4
  • i get the idea, but wouldnt i only get the state of attribute of the product AFTER the save? i need to compare attribute "new" before and after the save to see if it changes... Oct 30, 2019 at 10:29
  • try using catalog_product_save_before event as well. Oct 30, 2019 at 10:31
  • Works like a charme, thanks alot. Still wanna find out why it doesnt work with the plugin tho :) Oct 30, 2019 at 11:45
  • Let me search it for you, pls mark it as a solution and up vote. thanks Oct 30, 2019 at 12:02
0

To change any code behaviour either you can use plugin or Observer.

Plugin:

  • You can use around plugin to change the behaviour or code of the function but if you want to change response of the function you can use after plugin.
  • But if you already have Observer event you can use that to change response of any event or function.

So, You can use event `catalog_product_save_after``

and just save update your product according to your state of the product.

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.