Get RuleId from Coupon Code in checkout\cart\item\default.phtml
-
21-02-2021 - |
Question
I have overridden the checkout\cart\item\default.phtml in my theme. To get the 'used' coupon code I've found below rules in other questions:
$getCoupon = $block->getLayout()->createBlock('Magento\Checkout\Block\Cart\Coupon');
$coupon_code = $getCoupon->getCouponCode();
This is working fine, however I need the RuleId so I can check whether the correct coupon code type is used.
In a class with DI I can resolve this with:
$ruleId = $this->coupon->loadByCode($coupon_code)->getRuleId();
// coupon => use Magento\SalesRule\Model\Coupon;
There is no such block that I can import so I can have access to the getRuleId function?
What is the correct manner to establish this?
Solution
Yes, you can get rule_id by coupon_code
Try this to get the rule id using helper
In your helper
<?php
namespace {Vendor}\{ModuleName}\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function __construct(
\Magento\SalesRule\Model\CouponFactory $couponFactory
) {
$this->couponFactory = $couponFactory;
}
public function getItem($code = '')
{
$code = 'XXXXXX'; //your coupon code which you've got on default.phtml
$collect = $this->couponFactory->create()->getCollection()->addFieldToFilter('code', $code);
$couponId = array();
foreach ($collect as $value) {
$couponId = $value->getRuleId();
}
print_r($couponId);
}}
then in your default.phtml
call this and pass the coupon code as a params to the helper function as below
$this->helper('{Vendor}\{ModuleName}\Helper\Data')->getItem($couponCode); //send the coupon code which you've got
Hope this helps :)
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange