Magento: Check if coupon / sales rule is applicable for product

Tweet about this on TwitterShare on LinkedInShare on Google+Share on FacebookEmail this to someone

Recently I had to implement something really interesting in Magento. My task was to check if coupon could be applied to product before the product is added in cart and coupon is submitted. I started implementing this validation on my own but after some digging in Magento core I found the best solution.

I constructed the snippet below after digging in Magento SalesRule module:

// Sales Rule Id of the coupon we want to validate
$ruleId = 359;

// Id of Product we want to validate
$productId = 884;

/** @var Mage_SalesRule_Model_Rule $salesRule */
$salesRule = Mage::getModel('salesrule/rule')->load($ruleId);

/** @var Mage_Catalog_Model_Product $product */
$product = Mage::getModel('catalog/product')->load($productId);

$item = new Varien_Object();
$item->setProduct($product);

$isValid = (bool) $salesRule->getActions()->validate($item);

var_dump($isValid); // true OR false

Hope this helps!

Your thoughts?

Tweet about this on TwitterShare on LinkedInShare on Google+Share on FacebookEmail this to someone