سؤال

I want to apply coupon code programmatically when the condition is true. If condition false coupon code should be not applied.

Please help me.

هل كانت مفيدة؟

المحلول

You can try this below code :

Construct Method :

protected $cart;

public function __construct(
  \Magento\Checkout\Model\Cart $cart
){
   $this->cart = $cart;
}

Then, you can use this below code in your function :

$cart = $this->cart;
$couponCode = 'your_coupon_code';
if(condition true)
{
    $quote = $cart->getQuote()->setCouponCode($couponCode)->collectTotals()->save();
} else {
    $quote = $cart->getQuote()->setCouponCode('')->collectTotals()->save();
}

Object Manager Method :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$couponCode = 'your_coupon_code';
if(condition true)
{
    $quote = $cart->getQuote()->setCouponCode($couponCode)->collectTotals()->save();
} else {
    $quote = $cart->getQuote()->setCouponCode('')->collectTotals()->save();
}

Note : Use construct method instead of object Manager.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top