in

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)
    {
        try 
            $product = $observer->getProduct();
            if (!empty($product)) 
                $productIds = [$product->getId()]; //here you can one or more product Ids in array
                //list of indexers
                $indexList = [
                    'catalog_category_product',
                    'catalog_product_category',
                    'catalog_product_attribute',
                    'cataloginventory_stock',
                    'inventory',
                    'catalogsearch_fulltext',
                    'catalog_product_price',
                    'catalogrule_product',
                    'catalogrule_rule'
                ];
 
                foreach ($indexList as $index) 
                    $categoryIndexer = $this->indexerRegistry->get($index);
                
                    //check is indexer is scheduled
                    if (!$categoryIndexer->isScheduled()) 
                        $categoryIndexer->reindexList($productIds);
                    
                
            
         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?

Comments

Leave a Reply

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

13 − 7 =

Loading…

0
AggregateError

AggregateError

PepsiCo

PepsiCo’s competitive strategy turned into KPIs