How to Get Coupon Code on Success Page in Magento 2

coupon-codesmagento2order-success-pageshopping-cart-price-rules

I am trying to get coupon code created in cart price rule from backend on success page.
I am doing it as: In Block file

public function getCouponCollection() {

    $om = \Magento\Framework\App\ObjectManager::getInstance();

    $array = [];

    $getRules = $om->create('Magento\SalesRule\Model\Rule')->getCollection();

    foreach ($getRules as $rule) {
    $array[] = ["value" => $rule->getId(), "label" => __( $rule->getName() ) ];
}

return $array;

}

and with Magento\SalesRule\Model\RuleRepository injected in constructor

/** @var \Magento\SalesRule\Model\RuleRepository $ruleRepository **/

public function getCouponByRuleId ($id) {

    $rule = $this->ruleRepository->getById($id);

    $rule->getDescription();
    $rule->getCondition();
}

In template file, I have:

<?php $a=$block->getCouponCollection();


if (!empty($a)) {
foreach ($a as $v) {
    $rule = $block->getCouponByRuleId($v["value"]);
    if ($rule) {
        echo $rule->getCouponCode();
        }
    }
}
?>

and it is not working, what needs to be added/corrected here..any help should be much appreciated.

Best Answer

question is not clear about coupon code. but after reading the comment it make clear you want to get coupon code based on 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();
    }
 }

Reference