Magento 2.1 Module – Record Product Changes and Changer

catalogevent-observermagento-2.1module

In Magento2.1, I want to make a module to record the product change and changer in database. I think I can use events and observers to achieve it. The catalog_product_save_after event maybe is a good beginning.

But, when I use the event, how can I know what is the specific attribute the user changed? For example, the price change. How can I know the user changed the price, instead of changing anything else?

Maybe Magento2 has a better event for the specific attribute change? Or a good way to distinguish the price change or anything else? Any suggestion is welcome, thanks 🙂

Best Answer

Event

Use the catalog_product_save_after event in the Vendor/Model/etc/adminhtml/events.xml

<?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="the_observer_name" instance="Vendor\Module\Observer\ProductSaveAfter" />
    </event>
</config>

Observer

In the Observer, use the $observer->getProduct()->getOrigData('...') is the point to get specific attribute change.

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class ProductSaveAfter implements ObserverInterface
{
    public function execute(Observer $observer)
    {
        $product = $observer->getProduct();
        // you could add more product attributes to the $compareArray
        $compareArray = ['sku','price','special_price','cost','weight','special_from_date','special_to_date','status','visibility','is_salable'];
        $event = "";
        foreach ($compareArray as $value) {
            $old = $product->getOrigData($value);
            $new = $product->getData($value);
            if ($old !== $new) {
                $event .= " Change $value $old=>$new.";
            }
        }
        // other codes and write the $event to DB
    }
}

In the Observer, use the Magento\Backend\Model\Auth\Session to get the changer.

<?php
namespace Vendor\Module\Observer;

use Magento\Backend\Model\Auth\Session;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class ProductSaveAfter implements ObserverInterface
{
    protected $authSession;

    public function __construct(
        Session $authSession
    )
    {
        $this->authSession = $authSession;
    }

    public function execute(Observer $observer)
    {
        $user = $this->authSession->getUser();
        $userId = $user->getId();
        $userName = $user->getUsername();
        // other codes
    }
}

Merge above two Observer parts, now you get the product changes and changer, write them to the DB, then the function is finished.

Related Topic