Magento2 code snippets

Magento2 code snippets

This articles gives some useful Magento2 code snippets. To know more about magento2 click here.

Order state update

To update the order state and and status pro-grammatically in order define the status and state in this format. Initiate order object in the construct function and use that order object in the custom function to update it.

   To update order state programmatically in model, get order object from the construct function. 

    public function __construct(
	\Magento\Sales\Model\Order $order
    ){
    	$this->order = $order;	
    }
    public function updateorder(){
	    $order = $this->order;
	    $order->setState(\Magento\Sales\Model\Order::STATE_PROCESSING, true);
	    $order->setStatus(\Magento\Sales\Model\Order::STATE_PROCESSING);
	    $order->addStatusToHistory($order->getStatus(), 'Order processed successfully with reference');
	    $order->save();
    }

Exception handling

To use try catch exception in code, extend the exception class with use.

   use Exception;
   public function __construct (
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->_logger = $logger;
        
    }
 
   public function test(){
   	try{
     	    if(!value){
	    }else{
                throw new Exception('Value not exist');
            }
        }catch(Exception $e){
		 $this->_logger->addInfo($e->getMessage());
	}
   }

Get post value and set jsonresponse in controller

To create any api interface in magento 2 controller, you can get the request and set the json response with the following codes in controller.


<?php

namespace Explorer\Test\Controller\Sample;

use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
 
class Test extends \Magento\Framework\App\Action\Action
{
    protected $resultJsonFactory;

    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        
    }

    public function execute()
    {
       $request = $this->getRequest()->getPost();
       if(!value){
	   $response = array('status' => 'success');
       }else{
           $response = array('status' => 'failure');
       }
       
         $resultJson = $this->resultJsonFactory->create();
         if($response['status']=='failure'){
               $resultJson->setHttpResponseCode(\Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST);
         }
        return $resultJson->setData($response); 
    }
}

Trigger observer

When you are creating custom observer or need to trigger the core observer user the event manager object to trigger it.

   public function __construct(
	\Magento\Framework\Model\Context $context,
   ){
   	$this->_eventManager = $context->getEventDispatcher();
   }

   public function testdispath(){
       $order = $this->order;
       $this->_eventManager->dispatch(
            'test_method_is_active',
            [
                'order' => $order
            ]
        );
   }

New order email

To trigger new order email programmatically, you can do that from sendneworder function in magento 1. In magento 2, you need to use the send function in order sender class.

    $orderid = '10000000';
    $order = $this->_objectManager->get('Magento\Sales\Model\Order')->loadByIncrementId($orderid);
    $this->_objectManager->get('Magento\Sales\Model\Order\Email\Sender\OrderSender')->send($order);

No Comments yet, your thoughts are most welcome