how to get a coupon code in magento 2.right now i am getting name i want a coupon code
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collection,
\Magento\Framework\Stdlib\DateTime\Timezone $_stdTimezone,
array $data = []
) {
$this->_coreRegistry = $registry;
$this->collection = $collection;
$this->coupon = $coupon;
$this->_stdTimezone = $_stdTimezone;
parent::__construct($context, $data, $collection, $coupon);
}
public function getDiscountCoupon()
{
$currentTime = $this->_stdTimezone->date()->format('Y-m-d');
$rules = $this->collection->create()
->addFieldToFilter('is_active', 1)
->addFieldToFilter('to_date', ['gteq' => $currentTime]);
//echo $rules->getSelect()->__toString(); die();
$product = $this->_coreRegistry->registry('product');
foreach ($rules as $rule) {
try {
if ($rule->getActions()->validate($product)) {
$activeRules[] = $rule;
}
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
continue;
}
}
$rulesApplied = "<h3>Applicable Offers:</h3>";
foreach ($rules as $rule) {
$rulesApplied .= $rule->getName()."</br>";
}
return $rulesApplied;
}
Solutions
Please try $rule->getData('coupon_code')
instead of $rule->getName()
. Just take care that not all cart rules will have a coupon code, and if you created multiple coupon codes for a single rule, this won't work either.