Simply I just want to get the catalog price rules applied to products during checkout. I know a lot of solution is out from some sources for Magento 1, an example is this blog https://jutesenthil.wordpress.com/2015/09/28/get-catalog-rule-by-product-id-in-magento/ but trying to get same result in Magento 2 does not seem to be working. my code snippet is below.
/**
* @param $productId
* @param $customerGroupId
* @return mixed
*/
public function getCatalogPriceRuleFromProduct($productId, $customerGroupId)
{
/**
* @var MagentoCatalogModelProductFactory
*/
$product = $this->_objectManager->create('MagentoCatalogModelProductFactory')->create()->load($productId);
$storeId = $product->getStoreId();
$store = $this->_store_manager->getStore($storeId);
$websiteId = $store->getWebsiteId();
/**
* @var MagentoFrameworkStdlibDateTimeDateTime
*/
$date = $this->_objectManager->create('MagentoFrameworkStdlibDateTimeDateTime');
$dateTs = $date->gmtDate();
/**
* @var MagentoCatalogRuleModelRule
*/
$resource = $this->_objectManager->create('MagentoCatalogRuleModelRule');
// $resource = $this->_objectManager->create('MagentoCatalogRuleModelRuleFactory');
$rules = $resource->getRulesFromProduct($dateTs, $websiteId, $customerGroupId, $productId);
/*$rules = $resource->getCollection()
->addFieldToFilter('from_time', $dateTs)
->addFieldToFilter('to_time', $dateTs)
->addFieldToFilter('product_id', $productId)
->addFieldToFilter('store_id', $storeId)
->addFieldToFilter('website_id', $websiteId)
->addFieldToFilter('customer_group_id', $customerGroupId);*/
return $rules;
}
But always returning null.
Any help or ideas to go about this??
2
Answers
For anyone that requires this solution this is it
and if you need to get the actual discount amount just use this piece of code as well.
All thanks to @Pallavi
For getting all rules applied in your cart:
You can check
vendor/magento/module-sales-rule/Observer/SalesOrderAfterPlaceObserver.php
file for looping through rules.What I see in your code is , you are trying to call $resource->getRulesFromProduct() and your class is MagentoCatalogRuleModelRule. Try calling MagentoCatalogRuleModelResourceModelRule instead. This should work!