Different types of Cancel events for Orders in Magento 2

There are many events are available in Native Magento 2 but some of the difficult events of cancel action of payment, invoice or order are as below,

1. order_cancel_after

This event is used after order canceled. If you want to do something after an order is canceled you can use this event.
Check file, vendor/magento/module-sales/Model/Order.php at cancel() function.

$this->_eventManager->dispatch('order_cancel_after', ['order' => $this]);

2. sales_order_invoice_cancel

Allows you to cancel the order invoice when you canceled the order.
Check event called at, file, vendor/magento/module-sales/Model/Order/Invoice.php at cancel() function.

$this->_eventManager->dispatch('sales_order_invoice_cancel', [$this->_eventObject => $this]);

3. sales_order_payment_cancel_invoice

Allows you to cancel the order invoice when you canceled the order.
Check event called at, file, vendor/magento/module-sales/Model/Order/Invoice.php at cancel() function.

$this->_eventManager->dispatch('sales_order_invoice_cancel', [$this->_eventObject => $this]);

4. sales_order_payment_cancel_creditmemo

Event defined under vendor/magento/module-sales/Model/Order/Payment.php using cancelCreditmemo() function but this function is not called at any file. Might be used in future developments. This event contains payment and specified creditmemo object.

$this->_eventManager->dispatch(
            'sales_order_payment_cancel_creditmemo',
            ['payment' => $this, 'creditmemo' => $creditmemo]
        );

5.sales_order_payment_cancel_invoice

Cancel specified invoice from order and update self-total from order invoice.
Event defined under vendor/magento/module-sales/Model/Order/Payment.php

$this->_eventManager->dispatch(
            'sales_order_payment_cancel_invoice',
            ['payment' => $this, 'invoice' => $invoice]
        );

This event contains payment and invoice object.

6. sales_order_creditmemo_cancel

When you want to refund from a specific order or specific item from order,
Your best suitable event is, sales_order_creditmemo_cancel

$this->eventManager->dispatch('sales_order_creditmemo_cancel', ['creditmemo' => $creditmemo]);

 

 

 

How to cancel order programmatically in magento 2?

In Magento 2 we can cancel an order using below way, Pass Magento/Sales/Api/OrderManagementInterface as DI to __construct() function. We can use Interface method to cancel the order in Magento 2.

Below code snippets is used for cancel order.

<?php

public function __construct(
    \Magento\Sales\Api\OrderManagementInterface $orderManagement
) {
    $this->orderManagement = $orderManagement;
}
/**
 * int $orderId
 * Order cancel by order id $orderId 
 */
public function cancelOrder($orderId) {
    try {
        $this->orderManagement->cancel($orderId);
        return __('You canceled the order successfully.');
    } catch (\Exception $e) {
        return __('You have not canceled the order.');
    }
}

Call function like below from template or any PHP file, $orderId Must be an integer.

$orderId = 1;
$this->cacelOrder($orderId);

The result will be getting based on order success like, You canceled the order successfully otherwise result will be like for error, You have not canceled the order.

How to get product stock qty and stock information by product id in Magento 2?

You can get Product stock related information using the Catalog Inventory module of Magento 2.

Magento\CatalogInventory\Api\StockRegistryInterface is used for getting Stock Information from the Product.

If you want to only get Product Quantity and Product status might be it’s in stock or not then refer Get Product quantity from product object

Let’ create Block file and call function from a block,

<?php
namespace Rbj\Stockinfo\Block;

class Stockinfo extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockItemRepository,
        array $data = []
    )
    {
        $this->stockItemRepository = $stockItemRepository;
        parent::__construct($context, $data);
    }
    /* Using Product id */
    public function getStockItem($productId)
    {
        return $this->stockItemRepository->getStockItem($productId);
    }
    /* Using Product SKU */
    public function getStockItemBySku($productSku)
    {
        return $this->stockItemRepository->getStockItemBySku($productSku);
    }
}

Now, We can get the product stock information by id and SKU in a template file using the below way.

$id = 1; //Product id
/* by Product id */
$productStockById = $block->getStockItem($id);

/* by Product SKU */
$sku = '24-MB01';
$productStockBySku = $block->getStockItemBySku($sku);
echo "<pre>";print_r($productStockBySku->debug());

The output will be something like below,

Array
(
    [item_id] => 1
    [product_id] => 1
    [stock_id] => 1
    [qty] => 100.0000
    [min_qty] => 0.0000
    [use_config_min_qty] => 1
    [is_qty_decimal] => 0
    [backorders] => 0
    [use_config_backorders] => 1
    [min_sale_qty] => 1.0000
    [use_config_min_sale_qty] => 1
    [max_sale_qty] => 10000.0000
    [use_config_max_sale_qty] => 1
    [is_in_stock] => 1
    [notify_stock_qty] => 1.0000
    [use_config_notify_stock_qty] => 1
    [manage_stock] => 1
    [use_config_manage_stock] => 1
    [stock_status_changed_auto] => 0
    [use_config_qty_increments] => 1
    [qty_increments] => 1.0000
    [use_config_enable_qty_inc] => 1
    [enable_qty_increments] => 0
    [is_decimal_divided] => 0
    [website_id] => 0
    [type_id] => simple
)

You can get qty, min_sale_qty, is_in_stock, backorder, stock_id, website_id related data with ease.