Reindexing for one product in Magento 2

Reindexing for one product in Magento 2

Hello Friends!
In this blog, we will learn how we can do reindexing for one product programmatically.

In Magento 2, when we create a new product or update an existing product, sometimes its inventory and prices don’t update on frontend. And we don’t want to execute the reindexing command from CLI after each change.

In that case, we can create an observer on ‘controller_action_catalog_product_save_entity_after‘ event, which is dispatched in /Magento/Catalog/Controller/Adminhtml/Product/Save Controller class in Magento 2.
And if we are creating or updating a product programmatically then we can add the following code statements in our code.
Here, I have done this in AdminProductSaveAfterObserver.php file inside app/code/Vendor/CustomModule/Observer/ directory.

indexerRegistry = $indexerRegistry;

     * Product save after observer
     * @param MagentoFrameworkEventObserver $observer

    public function execute(MagentoFrameworkEventObserver $observer)
            $product = $observer->getProduct();
            if (!empty($product)) 
                $productIds = [$product->getId()]; //here you can one or more product Ids in array
                //list of indexers
                $indexList = [
                foreach ($indexList as $index) 
                    $categoryIndexer = $this->indexerRegistry->get($index);
                    //check is indexer is scheduled
                    if (!$categoryIndexer->isScheduled()) 
         catch (Exception $e) 
            echo $e->getMessage();

Hope this will be helpful. Thanks 🙂

Previous Blog: Display dependent fields on Customer Account Edit Page

Source link

What do you think?


Leave a Reply

Your email address will not be published. Required fields are marked *

13 − 7 =





PepsiCo’s competitive strategy turned into KPIs