Skip to content

Instantly share code, notes, and snippets.

@gelanivishal
Last active February 25, 2017 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gelanivishal/f76636c5cf3a227c673fe2ccc1879540 to your computer and use it in GitHub Desktop.
Save gelanivishal/f76636c5cf3a227c673fe2ccc1879540 to your computer and use it in GitHub Desktop.
Magento 2 code snippets

Magento2 code snippets

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();
}

New order email

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

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());
 }
}

How to load the Magento 2 core (external file)

<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    require 'app/bootstrap.php';

    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $app = $bootstrap->createApplication('Magento\Framework\App\Http');
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $objectManager->get('Magento\Framework\App\State')->setAreaCode('frontend'); // adminhtml

    // $bootstrap->run($app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment