:::: MENU ::::

how to retrieve coupon code by rule id magento 2

Recent QuestionsCategory: Magento 2 Questionshow to retrieve coupon code by rule id magento 2
Ajwad Taqvi asked 2 months ago

I have cart rule collection created at admin side and displaying rule names in the system configuration of the custom module. Actually, I wanted to get coupon code of a cart rule that has been selected by admin in system configuration and display it on success page for customer to use it in next order

1 Answers
Best Answer
qaisarsatti Staff answered 2 months ago

hi ajwad,

I am guessing you are storing the rule id. so here is code to get coupon from rule id.

namespace QaisarSatti\Module\Block;

class CouponCode extends \Magento\Framework\View\Element\Template
{

  protected $rule;  


  public function __construct(
     
        \Magento\SalesRule\Model\RuleFactory $rule

    ) {


        $this->rule = $rule;
     
    }
    public function getCouponCode()
    {
        $ruleId = 7;
        $couponCodeData = $this->rule->create()->load($ruleId);
        echo $couponCodeData->getCouponCode();
    }

}