Skip to content

How to create catalog price rule while initializing module?

I’m trying to create catalog rule by installing the module, but it’s not working.
This is my CreateRuleSetupInstallData.php file

<?php
namespace PerspectiveCreateRuleSetup;

use Exception;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;

class InstallData implements InstallDataInterface
{
    /**
     * @var MagentoFrameworkSetupModuleDataSetupInterface
     */
    private $moduleDataSetup;

    /**
     * @var MagentoCatalogRuleModelRuleFactory
     */
    private $ruleFactory;

    /**
     * @var MagentoCatalogRuleModelCatalogRuleRepository
     */
    private $catalogRuleRepository;

    public function __construct(
        MagentoFrameworkSetupModuleDataSetupInterface $moduleDataSetup,
        MagentoCatalogRuleModelRuleFactory $ruleFactory,
        MagentoCatalogRuleModelCatalogRuleRepository $catalogRuleRepository
    )
    {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->ruleFactory = $ruleFactory;
        $this->catalogRuleRepository = $catalogRuleRepository;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $this->moduleDataSetup->startSetup();
        
        $rule = $this->ruleFactory->create()
        ->setName('PriceDiscountCron Rule')
        ->setDescription('Rule from Price Discount Module')
        ->setIsActive(0) 
        ->setCustomerGroupIds(array(1))
        ->setWebsiteIds(array(1)) 
        ->setFromDate('') 
        ->setToDate('') 
        ->setSimpleAction('by_percent') 
        ->setDiscountAmount(10) 
        ->setStopRulesProcessing(0);

        try {
            $this->catalogRuleRepository->save($rule);
        } catch (Exception $e) {                    
           echo $e->getMessage();
        }

        $this->moduleDataSetup->endSetup();
    }
}

I found out new error

enter image description here