0

Actually i am trying to reindex category data while saving category from backend but i am getting an error DDL statements are not allowed in transactions in log file while reindexing programmatically. Please check below code.

Vendor\Module\etc\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_category_save_after">
        <observer name="categoryreindex" instance="Vendor\Module\Observer\Categoryreindex"/>
   </event>

</config>

Vendor\Module\Observer\Categoryreindex.php

<?php 
namespace Vendor\Module\Observer; 

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

class Categoryreindex implements ObserverInterface { 


    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $_logger;

    /**
     * @var \Magento\Indexer\Model\IndexerFactory
     */
    protected $_indexerFactory;


    public $indexerIds = array('catalog_category_product','catalog_product_category');

    public function __construct( 
        \Psr\Log\LoggerInterface $logger,
        \Magento\Indexer\Model\IndexerFactory $indexerFactory
    ){
        $this->_logger = $logger;
        $this->_indexerFactory = $indexerFactory;
    }


    /**
    * @param \Magento\Framework\Event\Observer $observer
    * @return void
    */
    public function execute(EventObserver $observer) { 

        try{
             $this->reIndexing(); // Running Reindexing programmatically 
             $this->_logger->info("Category Save Reindex....");

        } catch(\Exception $e) {
            $this->_logger->info("Category Save Reindexing Exception Message....".$e->getMessage());
        }
    }


    /**
    * Reindexing Category States programmatically 
    * @param none
    */
    public function reIndexing() {
       $indexerIds = $this->indexerIds;

       foreach ($indexerIds as $indexerId):
            $indexer = $this->_indexerFactory->create();
            $indexer->load($indexerId);
            $indexer->reindexAll();
       endforeach; 
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.