0

SalesQuoteCollectTotalsBefore

This observer will dispatch when the shipment is selected. After that, I need to apply a coupon code.

public function execute(\Magento\Framework\Event\Observer $observer)
{    

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cart = $objectManager->get('\Magento\Checkout\Model\Cart');

    $couponCode = "FIRSTORDER";
    $quote = $cart->getQuote()->setCouponCode($couponCode)
                              ->collectTotals()
                              ->save(); 
}

I created a coupon code FIRSTORDER. But I try to execute the function I am getting the following error.

"SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"

How to solve this issue?. How can I apply the coupon code? please share your valuable feedback

  • Try this code: $quote = $observer->getQuote(); $couponCode = "FIRSTORDER"; $quote->setCouponCode($couponCode)->collectTotals() ->save(); "OR" $quote = $observer->getQuote(); $couponCode = "FIRSTORDER"; $quote->setCouponCode($couponCode)->collectTotals(); – Abdul Feb 21 '18 at 7:13
  • Which observer you have tried? – Sohel Rana Feb 21 '18 at 7:25
  • @Abdul I tried but it still getting the same error. totaly stcuk – Midlaj Feb 21 '18 at 7:25
  • i have tried sales_quote_collect_totals_before this observer @SohelRana. But I remove the setcupon everything clear. there is no errors. – Midlaj Feb 21 '18 at 7:26
1

Try following way:


namespace SR\Stackexchange\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class SalesQuoteCollectTotalsBefore implements ObserverInterface
{
    public function execute(EventObserver $observer)
    {
        $quote = $observer->getEvent()->getQuote();
        $couponCode = "FIRSTORDER";
        $quote->setCouponCode($couponCode)
            ->save();

        return $this;
    }
}

Tested with M2.2 working fine.

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.