How to create creditmemo for order item programmatically in magento 2?

We can create credit memo for the specific item based on below way in Magento 2. We need to pass some basic data to generate credit memo in Magento 2. Continue reading “How to create creditmemo for order item programmatically in magento 2?”

How to get Shipping and Billing address from Order in magento 2?

In Magento 2 we can get Customer billing and Shipping address by order id using below code snippet,
Sometimes we required billing or shipping address of specific order placed by the customer we can get billing and shipping address by order id,
Using Block file get customer order’s billing and shipping address,

<?php

namespace Rbj\Address\Block;

class AddressFromOrder extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Sales\Model\ResourceModel\Order\Address\CollectionFactory $addressCollection
        array $data = []
    ) {
        $this->orderRepository = $orderRepository;
        $this->addressCollection = $addressCollection;
        parent::__construct($context, $data);
    }

    /**
      *@param int $id The order ID.
      */
    public function getOrderData($id)
    {
        try {
            $order = $this->orderRepository->get($id);
        } catch (NoSuchEntityException $e) {
            throw new \Magento\Framework\Exception\LocalizedException(__('This order no longer exists.'));
        }
    }

    /* get Shipping address data of specific order */
    public function getShippingAddress($orderId) {
        $order = $this->getOrderData($orderId);
        /* check order is not virtual */
        if(!$order->getIsVirtual()) {
            $orderShippingId = $order->getShippingAddressId();
            $address = $this->addressCollection->create()->addFieldToFilter('entity_id',array($orderShippingId))->getFirstItem();
            return $address;
        }
        return null;
    }

    /* get Billing address data of specific order */
    public function getBillingAddress($orderId) {
        $order = $this->getOrderData($orderId);
        $orderBillingId = $order->getBillingAddressId();
        $address = $this->addressCollection->create()->addFieldToFilter('entity_id',array($orderBillingId))->getFirstItem();
        return $address;

    }
}

Call a required function in the template file, You need to pass Order id to below function. Using Order Id we can get Customer billing and shipping address id and based on respective id we can get billing and shipping address.

<?php
$orderId = 1;

$shippingAddress = $block->getShippingAddress($orderId); // return shipping address array
$billingAddress = $block->getBillingAddress($orderId);// return billing address array
?>

 

How to create Shipment programmatically in magento 2?

We just need to pass order id in generateShipment($orderId) function from template.
below code snippet is used for generating Shipment in Magento 2, After generating Shipment automatically send the Shipment mail to a customer who has placed the order.

<?php
namespace Rbj\Shipment\Block;

class Shipment extends \Magento\Framework\View\Element\Template
{
public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Sales\Model\Convert\OrderFactory $convertOrderFactory,
        \Magento\Framework\DB\TransactionFactory $transactionFactory,
        \Magento\Sales\Model\Order\Email\Sender\ShipmentSender $shipmentSender,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        array $data = []
    ) {
        $this->orderRepository = $orderRepository;
        $this->orderConverter = $convertOrderFactory->create();
        $this->transactionFactory = $transactionFactory;
        $this->messageManager = $messageManager;
        $this->shipmentSender = $shipmentSender;
        parent::__construct($context, $data);
    }
/**
 * Create Shipment Based on Order Object
 * @param \Magento\Sales\Model\Order $order
 * @return $this
 */
public function generateShipment($orderId)
{
    try {
        $order = $this->orderRepository->get($orderId);
        if (!$order->getId()) {
            throw new \Magento\Framework\Exception\LocalizedException(__('The order no longer exists.'));
        }

        /* check shipment exist for order or not */
        if ($order->canShip())
        {
            // Initialize the order shipment object
            $shipment = $this->orderConverter->toShipment($order);
            foreach ($order->getAllItems() AS $orderItem) {
                // Check if order item has qty to ship or is order is virtual
                if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
                    continue;
                }
                $qtyShipped = $orderItem->getQtyToShip();
                // Create shipment item with qty
                $shipmentItem = $this->orderConverter->itemToShipmentItem($orderItem)->setQty($qtyShipped);
                // Add shipment item to shipment
                $shipment->addItem($shipmentItem);
            }
            // Register shipment
            $shipment->register();

            $shipment->getOrder()->setIsInProcess(true);

            try {
                $transaction = $this->transactionFactory->create()->addObject($shipment)
                    ->addObject($shipment->getOrder())
                    ->save();
                echo $shipmentId = $shipment->getIncrementId();
            } catch (\Exception $e) {
                $this->messageManager->addError(__('We can\'t generate shipment.'));
            }

            if ($shipment) {
                try {
                    $this->shipmentSender->send($shipment);
                } catch (\Exception $e) {
                    $this->messageManager->addError(__('We can\'t send the shipment right now.'));
                }
            }

            return $shipmentId;
        }
    } catch (\Exception $e) {
        $this->messageManager->addError($e->getMessage());
    }

    return true;
}

Call function from the template,

$orderId = 1;
$shipment = $block->generateInvoice($orderId);

Now Check from Admin panel.

Sales -> Order, Order with Id 1 has generated Shipment.