Reading list Switch to dark mode

    Reindexing for one product in Magento 2

    Updated 23 September 2021

    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.

     * Vendor Desc.
     * php version 7.3.*
     * @category  Vendor
     * @package   Vendor_CustomModule
     * @author    Vendor
     * @copyright Copyright (c) Vendor
     * @license
    namespace Vendor\CustomModule\Observer;
    use Magento\Framework\Event\ObserverInterface;
    class AdminProductSaveAfterObserver implements ObserverInterface
         * @var \Magento\Framework\Indexer\IndexerRegistry
        protected $indexerRegistry;
         * Object intialization
         * @param \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry
        public function __construct(
            \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry
        ) {
            $this->indexerRegistry = $indexerRegistry;
         * Product save after observer
         * @param \Magento\Framework\Event\Observer $observer
        public function execute(\Magento\Framework\Event\Observer $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 = [
                    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

    Next Blog: Detect your device is Mobile or Desktop in Magento 2

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

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

    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home