2

I need to get the details of an already created discount rule in magento 2.

I am using this code but don't work

public function __construct(
    \Magento\SalesRule\Model\Coupon $coupon
)
{
    $this->coupon = $coupon;
    parent::__construct($context);
}

...

public function getDiscount($couponCode)
{
    $ruleId =   $this->coupon->loadByCode($couponCode)->getRuleId();
    return $ruleId;

}
3

I wasn't that far from the solution:

protected $coupon;
protected $saleRule;     

public function __construct(
    \Magento\SalesRule\Model\Coupon $coupon,
    \Magento\SalesRule\Model\Rule $saleRule
)
{
    $this->coupon = $coupon;
    $this->saleRule = $saleRule;
    parent::__construct($context);
}

...

public function getDiscount($couponCode)
{
    $ruleId =   $this->coupon->loadByCode($couponCode)->getRuleId();
    $rule = $this->saleRule->load($ruleId);
    return $rule->getDiscountAmount();
}

Of course need a bit of validation to be sure the rule exist

1

As per Magento 2 coding standards, we should user API interface instead of direct use of the model.

protected $couponModel;

protected $ruleRepository;     

public function __construct(
    \Magento\SalesRule\Model\Coupon $couponModel,
    \Magento\SalesRule\Api\RuleRepositoryInterface $ruleRepository
) {
    $this->couponModel = $coupon;
    $this->ruleRepository = $saleRule;
}


public function getDiscount($couponCode)
{
    $ruleId =  $this->couponModel->loadByCode($couponCode)->getRuleId();
    $rule = $this->ruleRepository->getById($ruleId);
    return $rule->getDiscountAmount();
}

Note: I used direct model \Magento\SalesRule\Model\Coupon because there is no method available to get the coupon by id in interface \Magento\SalesRule\Api\CouponRepositoryInterface

  • @Price Patel, is it possible to get all coupons collections.Actually i am creating coupons programmatically with skus conditions.now problem is that i am not able to get coupons data(here i want to get skus with coupons). – Hitesh Balpande Jul 24 '19 at 13:45
  • @HiteshBalpande Use Magento\SalesRule\Model\ResourceModel\Rule\Collection class with ->addFieldToFilter('coupon_type', 2) to get all coupon collection – Prince Patel Jul 24 '19 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.