Skip to content

conditions at cart rule mage2

I have problems creating cart rules, I don’t quite understand how it works, I need to programmatically create a rule that fulfills the following:

3% automatic discount if you have between 7 and 13 products with the “format” attribute equal to “polvo”.

please if someone can guide me… this is my base method.
**(i’m newbee at magento2 xd)

public function createRule()
    {
     $atttr_to_set='formato';
        $typeL = 'polvo';

        $cartPriceRuleL1 = $this->ruleFactory->create();
    $cartPriceRuleL1->setName('3% at 7-13unds ')
            ->setDescription('3% at 7-13unds')
            ->setFromDate('2023-03-01')
            ->setToDate(NULL)
            ->setCustomerGroupIds(array('0','1'))
            ->setIsActive(true)
            ->setIsAdvanced('1')
            ->setProductIds(NULL)
            ->setSimpleAction(RuleInterface::DISCOUNT_ACTION_BY_PERCENT)
            ->setDiscountAmount('3')
            ->setDiscountQty(13)
            ->setDiscountStep(7)
            ->setCouponType(RuleInterface::COUPON_TYPE_NO_COUPON)
            ->setCouponCode(NULL)
            ->setUsesPerCoupon(NULL);
    $item_found = $this->foundProductRuleFactory->create()
            ->setType('MagentoSalesRuleModelRuleConditionProductFound')
            ->setValue(1) // 1 == found product
            ->setAggregator('all'); // match ALL conditions
        $cartPriceRuleL1->getConditions()->addCondition($item_found);


        $conditions = $this->productRuleFactory->create()
            ->setType('MagentoSalesRuleModelRuleConditionProduct')
            ->setAttribute('attribute',$atttr_to_set)
            ->setOperator('operator','==')
            ->setValue($typeL);
        $item_found->addCondition($conditions);
        $this->ruleResource->save($cartPriceRuleL1);}