I try to apply an existing coupon code programmatically in a controller by coupon id.

The only thing I found these code lines for Magento 1.


Does anyone know how can I do this in magento 2?

1 Answer 1


Use Checkout model session to get quote data.

 /** @var \Magento\Checkout\Model\Session $checkoutSession**/


Remember to inject \Magento\Checkout\Model\Session in your constructor.

Take a look: vendor/magento/module-checkout/Controller/Cart/CouponPost.php

  • so if my case i can use this code in my controller to apply an existing copon code? Jan 23, 2017 at 13:13
  • my controller look like this, and form here i want to appluy the coupon:public function execute() { $result = $this->resultJsonFactory->create(); if ($this->getRequest()->isAjax()) { $test= $this->getRequest()->getPost('key'); $sql ="SELECT code FROM salesrule_coupon WHERE code = '".$test."'"; $resource = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION); $values = $connection->fetchAll($sql); return $result->setData($values); Jan 23, 2017 at 13:15
  • Why use raw sql? Actually, I don't know what you're trying to do. You should inject \Magento\Checkout\Model\Session in your constructor. Jan 23, 2017 at 13:18
  • i create a dropdown button on payment page. the values of dropdown are actually a coupons codes id's, created by the default method. so when i chose a value from dropdown i send a ajax request with the value in my controller, and with that query i make sure that the coupon code exist in db, and then i try to apply the dscount. Jan 23, 2017 at 13:27
  • Seem that your question is too broad now. You should specify your question and more details. You can ask new question or update your question. Jan 23, 2017 at 13:29

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.