Skip to content

i need to create a observer that will change all products prices on category page

this is my events.xml code

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_price_change">
        <observer name="product_collection" instance="ObserverPriceObserverProduct"/>
    </event>
    <event name="product_price_change">
        <observer name="set_custom_price" instance="ObserverPriceObserverProduct" />
    </event>
</config>

this is my ObserverToChangePrice.php code :

<?php


namespace ObserverPriceObserver;

use MagentoFrameworkEventObserver as EventObserver;
use MagentoFrameworkEventObserverInterface;
class ObserverToChangePrice implements ObserverInterface
{
    protected $_productFactory;
    public function __construct(
        MagentoCatalogModelProductFactory $productFactory
    )
    {
        $this->_productFactory = $productFactory;
    }

    public function execute(EventObserver $observer)
    {
        $_collection = $observer->getCollection();
        $item = $observer->getEvent()->getData('quote_item');
        $price = 3;
        if ($item){
            $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
            $item->setCustomPrice($price);
            $item->setOriginalCustomPrice($price);
            $item->getProduct()->setIsSuperMode(true);
        }
        if ($_collection){
            foreach ($_collection as $_product) {
                $_product->setPrice($price);
                $_product->setFinalPrice($price);
                $_product->setTierPrice([000]);
            }
        }
        }
}

kindly help me with that
thanks …