how to retrieve coupon code by rule id magento 2

Questions

QuestionsCategory: Magento 2 Questionshow to retrieve coupon code by rule id magento 2
Ajwad Taqvi asked 6 years 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

0 Answers
Qaisar Satti Staff answered 6 years 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();
    }

}