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.

Call function from the template,

Now Check from Admin panel.

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

3 Replies to “How to create Shipment programmatically in magento 2?”

  1. Thank you rakesh, but i got the below error :
    Fatal error: Uncaught Exception: User Error: Some transactions have not been committed or rolled back in /public_html/vendor/magento/framework/DB/Adapter/Pdo/Mysql.php on line 3769 in /public_html/vendor/magento/framework/App/ErrorHandler.php:61 Stack trace: #0 [internal function]: MagentoFrameworkAppErrorHandler->handler(256, ‘Some transactio…’, ‘/home/…’, 3769, Array) #1 /public_html/vendor/magento/framework/DB/Adapter/Pdo/Mysql.php(3769): trigger_error(‘Some transactio…’, 256) #2 [internal function]: MagentoFrameworkDBAdapterPdoMysql->__destruct() #3 {main} thrown in /public_html/vendor/magento/framework/App/ErrorHandler.php on line 61

  2. And how to select sourceCode for shipment? We have multiple source for all websites. I have setup static sorucecode like below. $shipment->getExtensionAttributes()->setSourceCode('default'); How to get SourceCode from Order object?

Leave a Reply