0

I wrote the code for creating a Catalog rule in Magento 2.3.5 and after saving I have the code to re-index it automatically.

  /** @var \Magento\CatalogRule\Model\Rule $model */
                $ruleRepository = $this->_objectManager->get(
                    \Magento\CatalogRule\Api\CatalogRuleRepositoryInterface::class
                );
                $catalogRule = $this->_objectManager->create(\Magento\CatalogRule\Model\Rule::class);
                $ruleByBoRefId = $this->getRuleByBoRefId($boRefId);
                if (isset($ruleByBoRefId["rule_id"]) && $ruleId = $ruleByBoRefId["rule_id"]) {
                    $catalogRule = $ruleRepository->get($ruleId);
                }

                $catalogRule->loadPost($catalogRuleData);
                //$catalogRule->save();
                $ruleRepository->save($catalogRule);
                $this->reindexCatalogRule($catalogRule);

Code Reindex auto:

public function reindexCatalogRule($catalogRule){

    if($catalogRule->isRuleBehaviorChanged()){
        $this->_objectManager
            ->create(\Magento\CatalogRule\Model\Flag::class)
            ->loadSelf()
            ->setState(0)
            ->save();
    }

    $collection = $this->_indexerCollectionFactory->create()->getAllIds();
    foreach ($collection as $id) {
        $indexer = $this->_indexerFactory->create()->load($id);
        $indexer->getState()
            ->setStatus(\Magento\Framework\Indexer\StateInterface::STATUS_INVALID)
            ->save();
        $indexer->reindexAll();
    }
}

But after reindex the Rule still doesn't apply to the product. However, after I go to the admin and edited the previously saved catalog rule => Click Save => Then I ran the Indexer: reindex command of magento, the rule applies normally. I don't understand why like that. Please help me How to apply rules to products automatically ? Thanks

New contributor
Mr.John is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

Mr.John is a new contributor. Be nice, and check out our Code of Conduct.

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.