0

I am exploring the possibilities to show active Cart Price rules on a product page. For example, if I have a blue shirt in the category 'shirts' and I create a Cart Price rule for 20% discount on the category 'shirts', is it possible to check this for a product?

I'm trying to fetch all active cart price rules for a product. In the example of the shirt, I want to show 'Get 20% discount on all shirts' on that specific product page.

I explored the sales-rule module but did not find a possible solution. It should be possible right?

  • If this is the your requirement then create catalog price rule, why are you creating cart price rule ??? – Murtuza Zabuawala Dec 19 '17 at 11:22
  • @MurtuzaZabuawala if I create a catalog price rule, the new price is directly shown on catalog pages. I want to show it as a discount in the cart. – Silvan Dec 19 '17 at 11:23
2

Instead of Rule module you should look in

// Magento\Quote\Model\Quote\Item    
$item->getAppliedRuleIds() 

Cart contains items, items hold data about applied rules. From that point you will be able to say what rules are applied to a given item and you can do whatever you wish with that information.

  • Thanks for the answer. I see we can get this from a Quote item, but how can I get this for a normal product? – Silvan Dec 15 '17 at 10:49
  • You can't do that directly. All conditions for cart rules are serialized in conditions_serialized (salesrule table). You can try to deserialize these data and deduce what products if any and under what circumstances will trigger cart discount but that is awkward. Maybe a better solution would be to store that data directly on product. – Bartosz Herba Dec 15 '17 at 11:29
1

I got this fixed by using: \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collection.

I retrieve all rules with:

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

You could also filter this collection on Website and store filter.

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

$product->setProductId($product->getId());

    /** @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;
        }
    }

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.