2

How can I change the order status to "Processing" automatically if any specific coupon code has been applied during place order in Magento 2?

1

Finally I was able to get the required solution

  1. I have added a order status dropdown in add/edit coupon code form in admin area where admin can select the order status what will be set as the order status if that coupon code has been applied to the order.

  2. Add a field "order_status" to "salesrule" table.

  3. Then "sales_order_place_after" event, check the coupon code applied to the order and its selected order status, change the order status with respect to it.

Code:

event.xml

 <?xml version="1.0"?>
 <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

          <event name="sales_order_place_after">
             <observer name="change_order_status" instance="MPE\Coupon\Observer\ChangeOrderStatus"/>
          </event>
 </config>

ChangeOrderStatus.php

namespace MPE\Coupon\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class ChangeOrderStatus implements ObserverInterface{

    protected $_coupon;
    protected $_rule;

    public function __construct(
        \Magento\SalesRule\Model\Coupon $coupon,
        \Magento\SalesRule\Model\Rule $rule
    ){        
        $this->_coupon = $coupon;
        $this->_rule = $rule;
    }

    public function execute(EventObserver $observer){

        $order= $observer->getData('order');

        // Change Order status as per coupon code rule
        $coupon = $this->_coupon->loadByCode($order->getCouponCode());
        $salesRule = $this->_rule->load($coupon->getRuleId());        

        if($salesRule->getOrderStatus()){
            $order->setState($salesRule->getOrderStatus())->setStatus($salesRule->getOrderStatus());
            $order->addStatusToHistory($order->getStatus(), __('Order status has been changed with respect to coupon code rule.'));
            $order->save();
        }



    }
}

NOTE: $salesRule->getOrderStatus() is custom field that has been added to salesrule table.

Hope it will help someone. Also you can use this code as for sales_order_place_after event too.

0

For chnage order status we must palce the order but if you place th order you can't apply a coupon code

or if you need you can chnage the stauts of your order after placing the order with an observer

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.