0

Situation:

  • There are 4 products in the cart
  • One of these products causes a cart rule to apply

By getting the cart items via code, I need to be able to identify the one item that is causing the rule to apply.

My problem is that I cannot find a way to separate this item from the others in the cart, they all return the same results.

My code so far:

foreach($quote->getItems() as $quoteItem) {

$itemAppliedRulesId = $quoteItem->getAppliedRuleIds(); // I expect this to  give a result only for the one item that matches the cart rule, instead all the items returns the rule id

$product = $quoteItem->getProduct();
$result = $rule->getActions()->validate($product); // see comment above, same result

}

My question:

Is there a way I can get the items of the cart that cause one or more rules to apply?

2
  • are you looking for the cart rule or catalog rule? Jul 19 at 9:53
  • Hello @DhirenVasoya, thank you for your reply. I'm talking about the cart rules not the catalog rules.
    – Lou Nik
    Jul 19 at 11:33
0

Using: \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collection.

retrieve all rules with:

$rules = $this->collection->create();

After you retrieve the collection you can loop through all rules and check if you could apply the rule for the current product:

/** @var \Magento\SalesRule\Model\Rule $rule */
    foreach ($rules as $rule) {
        try {
            if ($rule->getActions()->validate($product)) {
                $activeRules[] = $rule;
            }
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            continue;
        }
    }
2
  • Hi, thank you for your reply. If you read my post, you can see that I have already tried to validate the product ($result = $rule->getActions()->validate($product)) but the validation returns the applied rule ids for each product in the cart, even those who do not comply to the rule conditions. It's like the $cart->appliedRulesId is copied in all cart items, despite whether they meet the conditions for the rule or not
    – Lou Nik
    Jul 29 at 14:43
  • You need to take out each product in the cart to check with the available rules. You need to do a loop for each product with each rule, if any rule is satisfied save it in an array then output the matching rules in your cart (you can see the code in my answer above) Aug 4 at 10:20

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.