Create shipment and invoice in mass actionAdd More Mass action in Order grid in magento2“Unknown columns” error when executing a mass actionMagento2: Dynamic Mass Action in Sales GridMagento 2: Grid mass action provides collection of MagentoFrameworkViewElementUiComponentDataProviderDocument instead of modelsMagento 2 : Add New Grid Mass Action based on conditionMass action in custom grid block Magento 2 not showingHow we can create partial shipment programmatically using rest apiMagento 2 add conditional mass action in sales order gridMagento2 Mass Action to Sales Order GridMagento 2 Mass shipment
Should we release the security issues we found in our product as CVE or we can just update those on weekly release notes?
Awsome yet unlucky path traversal
Instead of Universal Basic Income, why not Universal Basic NEEDS?
How do anti-virus programs start at Windows boot?
Why is the President allowed to veto a cancellation of emergency powers?
Are ETF trackers fundamentally better than individual stocks?
How to read the value of this capacitor?
Why does Bach not break the rules here?
Do these spellcasting foci from Xanathar's Guide to Everything have to be held in a hand?
Why do passenger jet manufacturers design their planes with stall prevention systems?
Interplanetary conflict, some disease destroys the ability to understand or appreciate music
Do I need life insurance if I can cover my own funeral costs?
Define, (actually define) the "stability" and "energy" of a compound
Gravity magic - How does it work?
Unexpected result from ArcLength
How to simplify this time periods definition interface?
What options are left, if Britain cannot decide?
Identifying the interval from A♭ to D♯
How can I track script which gives me "command not found" right after the login?
What do Xenomorphs eat in the Alien series?
Python if-else code style for reduced code for rounding floats
A link redirect to http instead of https: how critical is it?
How to use deus ex machina safely?
SOQL: Populate a Literal List in WHERE IN Clause
Create shipment and invoice in mass action
Add More Mass action in Order grid in magento2“Unknown columns” error when executing a mass actionMagento2: Dynamic Mass Action in Sales GridMagento 2: Grid mass action provides collection of MagentoFrameworkViewElementUiComponentDataProviderDocument instead of modelsMagento 2 : Add New Grid Mass Action based on conditionMass action in custom grid block Magento 2 not showingHow we can create partial shipment programmatically using rest apiMagento 2 add conditional mass action in sales order gridMagento2 Mass Action to Sales Order GridMagento 2 Mass shipment
I want to create shipment + Invoice using mass action in order grid.
Can anyone tell me the approach to do this?
Share code if possible otherwise approach would be good.
Thanks.
magento2
New contributor
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
I want to create shipment + Invoice using mass action in order grid.
Can anyone tell me the approach to do this?
Share code if possible otherwise approach would be good.
Thanks.
magento2
New contributor
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Did you search for any tutorial?
– Shoaib Munir
15 hours ago
add a comment |
I want to create shipment + Invoice using mass action in order grid.
Can anyone tell me the approach to do this?
Share code if possible otherwise approach would be good.
Thanks.
magento2
New contributor
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
I want to create shipment + Invoice using mass action in order grid.
Can anyone tell me the approach to do this?
Share code if possible otherwise approach would be good.
Thanks.
magento2
magento2
New contributor
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 15 hours ago
Muhammad Bilal khanMuhammad Bilal khan
253
253
New contributor
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Muhammad Bilal khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Did you search for any tutorial?
– Shoaib Munir
15 hours ago
add a comment |
1
Did you search for any tutorial?
– Shoaib Munir
15 hours ago
1
1
Did you search for any tutorial?
– Shoaib Munir
15 hours ago
Did you search for any tutorial?
– Shoaib Munir
15 hours ago
add a comment |
1 Answer
1
active
oldest
votes
I recently worked on this feature both (Invoice and Shipment). First you have to add Uicomponent in your module
Path: appcodeVendorModuleviewadminhtmlui_componentsales_order_grid.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<massaction name="listing_massaction">
<action name="order_invoice">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_mass</item>
<item name="label" xsi:type="string" translate="true">Invoice</item>
<item name="url" xsi:type="url" path="ordermass/order/massInvoice"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Invoice</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create invoice for selected items?</item>
</item>
</item>
</argument>
</action>
<action name="order_ship">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_ship_mass</item>
<item name="label" xsi:type="string" translate="true">Ship (Email)</item>
<item name="url" xsi:type="url" path="ordermass/order/massShip"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Ship (Email)</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create shipment for selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
</listingToolbar>
</listing>
After that Add routes in your module
Path: appcodeVendorModuleetcadminhtmlroutes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="ordermass" frontName="ordermass">
<module name="Vendor_Module" />
</route>
</router>
</config>
For Invoice Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassInvoice.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassInvoice extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
/**
* @var MagentoSalesModelServiceInvoiceService
*/
protected $_invoiceService;
/**
* @var MagentoFrameworkDBTransaction
*/
protected $_transaction;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoSalesModelServiceInvoiceService $invoiceService,
MagentoFrameworkDBTransaction $transaction,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
$this->_invoiceService = $invoiceService;
$this->_transaction = $transaction;
protected function massAction(AbstractCollection $collection)
$countInvoiceOrder = 0; $NonInvoiceOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canInvoice())
// Create invoice for this order
$invoice = $this->_objectManager->create('MagentoSalesModelServiceInvoiceService')->prepareInvoice($loadedOrder);
//$invoice->getOrder()->setIsInProcess(true);
$invoice->setShippingAmount($loadedOrder->getShippingAmount());
$invoice->setBaseShippingAmount($loadedOrder->getBaseShippingAmount());
$invoice->setTaxAmount($loadedOrder->getTaxAmount());
$invoice->setBaseTaxAmount($loadedOrder->getBaseTaxAmount());
$invoice->setSubtotal($loadedOrder->getSubtotal());
$invoice->setBaseSubtotal($loadedOrder->getBaseSubtotal());
$invoice->setGrandTotal($loadedOrder->getGrandTotal());
$invoice->setBaseGrandTotal($loadedOrder->getBaseGrandTotal());
// Register as invoice item
$invoice->setRequestedCaptureCase(MagentoSalesModelOrderInvoice::CAPTURE_OFFLINE);
$invoice->register();
// Save the invoice to the order
$transaction = $this->_objectManager->create('MagentoFrameworkDBTransaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about invoice #%1. '.$appendusername, $invoice->getId())
)->setIsCustomerNotified(false)->save();
if ($loadedOrder->canShip())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus(MagentoSalesModelOrder::STATE_PROCESSING);
$loadedOrder->addStatusToHistory($loadedOrder->getStatus(), 'Order status set to processing using Mass Invoice action '.$appendusername);
$loadedOrder->save();
$countInvoiceOrder++;
else
if (empty($NonInvoiceOrdernuumbers))
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonInvoiceOrder = $collection->count() - $countInvoiceOrder;
if ($countNonInvoiceOrder && $countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
elseif ($countNonInvoiceOrder)
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
if ($countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
For Shipment Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassShip.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassShip extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
protected function massAction(AbstractCollection $collection)
$countShipOrder = 0; $NonShipOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canShip())
$convertOrder = $this->_objectManager->create('MagentoSalesModelConvertOrder');
$shipment = $convertOrder->toShipment($loadedOrder);
// Loop through order items
foreach ($order->getAllItems() AS $orderItem) $orderItem->getIsVirtual())
continue;
$qtyShipped = $orderItem->getQtyToShip();
// Create shipment item with qty
$shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);
// Add shipment item to shipment
$shipment->addItem($shipmentItem);
// Register shipment
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
try
// Save created shipment and order
$shipment->save();
$shipment->getOrder()->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about shipment #%1. '.$appendusername, $shipment->getId())
)->setIsCustomerNotified(false)->save();
$itemsCheck = $loadedOrder->getItemsCollection()->addAttributeToSelect('*')->load();
foreach ($itemsCheck as $item) $item->getIsVirtual())
continue;
$item->setQtyShipped($item->getQtyToShip());
$item->save();
$Norder = $shipment->getOrder()->load( $shipment->getOrder()->getId() );
$Norder->save();
// Send email
$this->_objectManager->create('MagentoShippingModelShipmentNotifier')
->notify($shipment);
$shipment->save();
catch (Exception $e)
$this->messageManager->addError(__($e->getMessage()));
if ($loadedOrder->canInvoice())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus('shipped');
$loadedOrder->addStatusToHistory('shipped', 'Order status set to shipped using Mass Ship action. '.$appendusername);
$loadedOrder->save();
$countShipOrder++;
else
if (empty($NonShipOrdernuumbers))
$NonShipOrdernuumbers = $NonShipOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonShipOrdernuumbers = $NonShipOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonShipOrder = $collection->count() - $countShipOrder;
if ($countNonShipOrder && $countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
elseif ($countNonShipOrder)
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
if ($countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
This is tested code, I hope this will help
1
+1 nice work around
– Prathap Gunasekaran
15 hours ago
Thanks mate @PrathapGunasekaran. Glad you found it useful.
– Muhammad Hasham
15 hours ago
1
Thanks Hasham. Really appreciate your effort on this
– Muhammad Bilal khan
15 hours ago
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Muhammad Bilal khan is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f266081%2fcreate-shipment-and-invoice-in-mass-action%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I recently worked on this feature both (Invoice and Shipment). First you have to add Uicomponent in your module
Path: appcodeVendorModuleviewadminhtmlui_componentsales_order_grid.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<massaction name="listing_massaction">
<action name="order_invoice">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_mass</item>
<item name="label" xsi:type="string" translate="true">Invoice</item>
<item name="url" xsi:type="url" path="ordermass/order/massInvoice"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Invoice</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create invoice for selected items?</item>
</item>
</item>
</argument>
</action>
<action name="order_ship">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_ship_mass</item>
<item name="label" xsi:type="string" translate="true">Ship (Email)</item>
<item name="url" xsi:type="url" path="ordermass/order/massShip"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Ship (Email)</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create shipment for selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
</listingToolbar>
</listing>
After that Add routes in your module
Path: appcodeVendorModuleetcadminhtmlroutes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="ordermass" frontName="ordermass">
<module name="Vendor_Module" />
</route>
</router>
</config>
For Invoice Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassInvoice.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassInvoice extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
/**
* @var MagentoSalesModelServiceInvoiceService
*/
protected $_invoiceService;
/**
* @var MagentoFrameworkDBTransaction
*/
protected $_transaction;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoSalesModelServiceInvoiceService $invoiceService,
MagentoFrameworkDBTransaction $transaction,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
$this->_invoiceService = $invoiceService;
$this->_transaction = $transaction;
protected function massAction(AbstractCollection $collection)
$countInvoiceOrder = 0; $NonInvoiceOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canInvoice())
// Create invoice for this order
$invoice = $this->_objectManager->create('MagentoSalesModelServiceInvoiceService')->prepareInvoice($loadedOrder);
//$invoice->getOrder()->setIsInProcess(true);
$invoice->setShippingAmount($loadedOrder->getShippingAmount());
$invoice->setBaseShippingAmount($loadedOrder->getBaseShippingAmount());
$invoice->setTaxAmount($loadedOrder->getTaxAmount());
$invoice->setBaseTaxAmount($loadedOrder->getBaseTaxAmount());
$invoice->setSubtotal($loadedOrder->getSubtotal());
$invoice->setBaseSubtotal($loadedOrder->getBaseSubtotal());
$invoice->setGrandTotal($loadedOrder->getGrandTotal());
$invoice->setBaseGrandTotal($loadedOrder->getBaseGrandTotal());
// Register as invoice item
$invoice->setRequestedCaptureCase(MagentoSalesModelOrderInvoice::CAPTURE_OFFLINE);
$invoice->register();
// Save the invoice to the order
$transaction = $this->_objectManager->create('MagentoFrameworkDBTransaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about invoice #%1. '.$appendusername, $invoice->getId())
)->setIsCustomerNotified(false)->save();
if ($loadedOrder->canShip())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus(MagentoSalesModelOrder::STATE_PROCESSING);
$loadedOrder->addStatusToHistory($loadedOrder->getStatus(), 'Order status set to processing using Mass Invoice action '.$appendusername);
$loadedOrder->save();
$countInvoiceOrder++;
else
if (empty($NonInvoiceOrdernuumbers))
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonInvoiceOrder = $collection->count() - $countInvoiceOrder;
if ($countNonInvoiceOrder && $countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
elseif ($countNonInvoiceOrder)
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
if ($countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
For Shipment Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassShip.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassShip extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
protected function massAction(AbstractCollection $collection)
$countShipOrder = 0; $NonShipOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canShip())
$convertOrder = $this->_objectManager->create('MagentoSalesModelConvertOrder');
$shipment = $convertOrder->toShipment($loadedOrder);
// Loop through order items
foreach ($order->getAllItems() AS $orderItem) $orderItem->getIsVirtual())
continue;
$qtyShipped = $orderItem->getQtyToShip();
// Create shipment item with qty
$shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);
// Add shipment item to shipment
$shipment->addItem($shipmentItem);
// Register shipment
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
try
// Save created shipment and order
$shipment->save();
$shipment->getOrder()->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about shipment #%1. '.$appendusername, $shipment->getId())
)->setIsCustomerNotified(false)->save();
$itemsCheck = $loadedOrder->getItemsCollection()->addAttributeToSelect('*')->load();
foreach ($itemsCheck as $item) $item->getIsVirtual())
continue;
$item->setQtyShipped($item->getQtyToShip());
$item->save();
$Norder = $shipment->getOrder()->load( $shipment->getOrder()->getId() );
$Norder->save();
// Send email
$this->_objectManager->create('MagentoShippingModelShipmentNotifier')
->notify($shipment);
$shipment->save();
catch (Exception $e)
$this->messageManager->addError(__($e->getMessage()));
if ($loadedOrder->canInvoice())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus('shipped');
$loadedOrder->addStatusToHistory('shipped', 'Order status set to shipped using Mass Ship action. '.$appendusername);
$loadedOrder->save();
$countShipOrder++;
else
if (empty($NonShipOrdernuumbers))
$NonShipOrdernuumbers = $NonShipOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonShipOrdernuumbers = $NonShipOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonShipOrder = $collection->count() - $countShipOrder;
if ($countNonShipOrder && $countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
elseif ($countNonShipOrder)
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
if ($countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
This is tested code, I hope this will help
1
+1 nice work around
– Prathap Gunasekaran
15 hours ago
Thanks mate @PrathapGunasekaran. Glad you found it useful.
– Muhammad Hasham
15 hours ago
1
Thanks Hasham. Really appreciate your effort on this
– Muhammad Bilal khan
15 hours ago
add a comment |
I recently worked on this feature both (Invoice and Shipment). First you have to add Uicomponent in your module
Path: appcodeVendorModuleviewadminhtmlui_componentsales_order_grid.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<massaction name="listing_massaction">
<action name="order_invoice">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_mass</item>
<item name="label" xsi:type="string" translate="true">Invoice</item>
<item name="url" xsi:type="url" path="ordermass/order/massInvoice"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Invoice</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create invoice for selected items?</item>
</item>
</item>
</argument>
</action>
<action name="order_ship">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_ship_mass</item>
<item name="label" xsi:type="string" translate="true">Ship (Email)</item>
<item name="url" xsi:type="url" path="ordermass/order/massShip"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Ship (Email)</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create shipment for selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
</listingToolbar>
</listing>
After that Add routes in your module
Path: appcodeVendorModuleetcadminhtmlroutes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="ordermass" frontName="ordermass">
<module name="Vendor_Module" />
</route>
</router>
</config>
For Invoice Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassInvoice.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassInvoice extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
/**
* @var MagentoSalesModelServiceInvoiceService
*/
protected $_invoiceService;
/**
* @var MagentoFrameworkDBTransaction
*/
protected $_transaction;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoSalesModelServiceInvoiceService $invoiceService,
MagentoFrameworkDBTransaction $transaction,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
$this->_invoiceService = $invoiceService;
$this->_transaction = $transaction;
protected function massAction(AbstractCollection $collection)
$countInvoiceOrder = 0; $NonInvoiceOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canInvoice())
// Create invoice for this order
$invoice = $this->_objectManager->create('MagentoSalesModelServiceInvoiceService')->prepareInvoice($loadedOrder);
//$invoice->getOrder()->setIsInProcess(true);
$invoice->setShippingAmount($loadedOrder->getShippingAmount());
$invoice->setBaseShippingAmount($loadedOrder->getBaseShippingAmount());
$invoice->setTaxAmount($loadedOrder->getTaxAmount());
$invoice->setBaseTaxAmount($loadedOrder->getBaseTaxAmount());
$invoice->setSubtotal($loadedOrder->getSubtotal());
$invoice->setBaseSubtotal($loadedOrder->getBaseSubtotal());
$invoice->setGrandTotal($loadedOrder->getGrandTotal());
$invoice->setBaseGrandTotal($loadedOrder->getBaseGrandTotal());
// Register as invoice item
$invoice->setRequestedCaptureCase(MagentoSalesModelOrderInvoice::CAPTURE_OFFLINE);
$invoice->register();
// Save the invoice to the order
$transaction = $this->_objectManager->create('MagentoFrameworkDBTransaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about invoice #%1. '.$appendusername, $invoice->getId())
)->setIsCustomerNotified(false)->save();
if ($loadedOrder->canShip())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus(MagentoSalesModelOrder::STATE_PROCESSING);
$loadedOrder->addStatusToHistory($loadedOrder->getStatus(), 'Order status set to processing using Mass Invoice action '.$appendusername);
$loadedOrder->save();
$countInvoiceOrder++;
else
if (empty($NonInvoiceOrdernuumbers))
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonInvoiceOrder = $collection->count() - $countInvoiceOrder;
if ($countNonInvoiceOrder && $countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
elseif ($countNonInvoiceOrder)
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
if ($countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
For Shipment Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassShip.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassShip extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
protected function massAction(AbstractCollection $collection)
$countShipOrder = 0; $NonShipOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canShip())
$convertOrder = $this->_objectManager->create('MagentoSalesModelConvertOrder');
$shipment = $convertOrder->toShipment($loadedOrder);
// Loop through order items
foreach ($order->getAllItems() AS $orderItem) $orderItem->getIsVirtual())
continue;
$qtyShipped = $orderItem->getQtyToShip();
// Create shipment item with qty
$shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);
// Add shipment item to shipment
$shipment->addItem($shipmentItem);
// Register shipment
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
try
// Save created shipment and order
$shipment->save();
$shipment->getOrder()->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about shipment #%1. '.$appendusername, $shipment->getId())
)->setIsCustomerNotified(false)->save();
$itemsCheck = $loadedOrder->getItemsCollection()->addAttributeToSelect('*')->load();
foreach ($itemsCheck as $item) $item->getIsVirtual())
continue;
$item->setQtyShipped($item->getQtyToShip());
$item->save();
$Norder = $shipment->getOrder()->load( $shipment->getOrder()->getId() );
$Norder->save();
// Send email
$this->_objectManager->create('MagentoShippingModelShipmentNotifier')
->notify($shipment);
$shipment->save();
catch (Exception $e)
$this->messageManager->addError(__($e->getMessage()));
if ($loadedOrder->canInvoice())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus('shipped');
$loadedOrder->addStatusToHistory('shipped', 'Order status set to shipped using Mass Ship action. '.$appendusername);
$loadedOrder->save();
$countShipOrder++;
else
if (empty($NonShipOrdernuumbers))
$NonShipOrdernuumbers = $NonShipOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonShipOrdernuumbers = $NonShipOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonShipOrder = $collection->count() - $countShipOrder;
if ($countNonShipOrder && $countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
elseif ($countNonShipOrder)
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
if ($countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
This is tested code, I hope this will help
1
+1 nice work around
– Prathap Gunasekaran
15 hours ago
Thanks mate @PrathapGunasekaran. Glad you found it useful.
– Muhammad Hasham
15 hours ago
1
Thanks Hasham. Really appreciate your effort on this
– Muhammad Bilal khan
15 hours ago
add a comment |
I recently worked on this feature both (Invoice and Shipment). First you have to add Uicomponent in your module
Path: appcodeVendorModuleviewadminhtmlui_componentsales_order_grid.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<massaction name="listing_massaction">
<action name="order_invoice">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_mass</item>
<item name="label" xsi:type="string" translate="true">Invoice</item>
<item name="url" xsi:type="url" path="ordermass/order/massInvoice"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Invoice</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create invoice for selected items?</item>
</item>
</item>
</argument>
</action>
<action name="order_ship">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_ship_mass</item>
<item name="label" xsi:type="string" translate="true">Ship (Email)</item>
<item name="url" xsi:type="url" path="ordermass/order/massShip"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Ship (Email)</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create shipment for selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
</listingToolbar>
</listing>
After that Add routes in your module
Path: appcodeVendorModuleetcadminhtmlroutes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="ordermass" frontName="ordermass">
<module name="Vendor_Module" />
</route>
</router>
</config>
For Invoice Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassInvoice.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassInvoice extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
/**
* @var MagentoSalesModelServiceInvoiceService
*/
protected $_invoiceService;
/**
* @var MagentoFrameworkDBTransaction
*/
protected $_transaction;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoSalesModelServiceInvoiceService $invoiceService,
MagentoFrameworkDBTransaction $transaction,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
$this->_invoiceService = $invoiceService;
$this->_transaction = $transaction;
protected function massAction(AbstractCollection $collection)
$countInvoiceOrder = 0; $NonInvoiceOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canInvoice())
// Create invoice for this order
$invoice = $this->_objectManager->create('MagentoSalesModelServiceInvoiceService')->prepareInvoice($loadedOrder);
//$invoice->getOrder()->setIsInProcess(true);
$invoice->setShippingAmount($loadedOrder->getShippingAmount());
$invoice->setBaseShippingAmount($loadedOrder->getBaseShippingAmount());
$invoice->setTaxAmount($loadedOrder->getTaxAmount());
$invoice->setBaseTaxAmount($loadedOrder->getBaseTaxAmount());
$invoice->setSubtotal($loadedOrder->getSubtotal());
$invoice->setBaseSubtotal($loadedOrder->getBaseSubtotal());
$invoice->setGrandTotal($loadedOrder->getGrandTotal());
$invoice->setBaseGrandTotal($loadedOrder->getBaseGrandTotal());
// Register as invoice item
$invoice->setRequestedCaptureCase(MagentoSalesModelOrderInvoice::CAPTURE_OFFLINE);
$invoice->register();
// Save the invoice to the order
$transaction = $this->_objectManager->create('MagentoFrameworkDBTransaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about invoice #%1. '.$appendusername, $invoice->getId())
)->setIsCustomerNotified(false)->save();
if ($loadedOrder->canShip())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus(MagentoSalesModelOrder::STATE_PROCESSING);
$loadedOrder->addStatusToHistory($loadedOrder->getStatus(), 'Order status set to processing using Mass Invoice action '.$appendusername);
$loadedOrder->save();
$countInvoiceOrder++;
else
if (empty($NonInvoiceOrdernuumbers))
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonInvoiceOrder = $collection->count() - $countInvoiceOrder;
if ($countNonInvoiceOrder && $countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
elseif ($countNonInvoiceOrder)
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
if ($countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
For Shipment Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassShip.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassShip extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
protected function massAction(AbstractCollection $collection)
$countShipOrder = 0; $NonShipOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canShip())
$convertOrder = $this->_objectManager->create('MagentoSalesModelConvertOrder');
$shipment = $convertOrder->toShipment($loadedOrder);
// Loop through order items
foreach ($order->getAllItems() AS $orderItem) $orderItem->getIsVirtual())
continue;
$qtyShipped = $orderItem->getQtyToShip();
// Create shipment item with qty
$shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);
// Add shipment item to shipment
$shipment->addItem($shipmentItem);
// Register shipment
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
try
// Save created shipment and order
$shipment->save();
$shipment->getOrder()->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about shipment #%1. '.$appendusername, $shipment->getId())
)->setIsCustomerNotified(false)->save();
$itemsCheck = $loadedOrder->getItemsCollection()->addAttributeToSelect('*')->load();
foreach ($itemsCheck as $item) $item->getIsVirtual())
continue;
$item->setQtyShipped($item->getQtyToShip());
$item->save();
$Norder = $shipment->getOrder()->load( $shipment->getOrder()->getId() );
$Norder->save();
// Send email
$this->_objectManager->create('MagentoShippingModelShipmentNotifier')
->notify($shipment);
$shipment->save();
catch (Exception $e)
$this->messageManager->addError(__($e->getMessage()));
if ($loadedOrder->canInvoice())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus('shipped');
$loadedOrder->addStatusToHistory('shipped', 'Order status set to shipped using Mass Ship action. '.$appendusername);
$loadedOrder->save();
$countShipOrder++;
else
if (empty($NonShipOrdernuumbers))
$NonShipOrdernuumbers = $NonShipOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonShipOrdernuumbers = $NonShipOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonShipOrder = $collection->count() - $countShipOrder;
if ($countNonShipOrder && $countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
elseif ($countNonShipOrder)
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
if ($countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
This is tested code, I hope this will help
I recently worked on this feature both (Invoice and Shipment). First you have to add Uicomponent in your module
Path: appcodeVendorModuleviewadminhtmlui_componentsales_order_grid.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<massaction name="listing_massaction">
<action name="order_invoice">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_mass</item>
<item name="label" xsi:type="string" translate="true">Invoice</item>
<item name="url" xsi:type="url" path="ordermass/order/massInvoice"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Invoice</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create invoice for selected items?</item>
</item>
</item>
</argument>
</action>
<action name="order_ship">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">order_ship_mass</item>
<item name="label" xsi:type="string" translate="true">Ship (Email)</item>
<item name="url" xsi:type="url" path="ordermass/order/massShip"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Ship (Email)</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to create shipment for selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
</listingToolbar>
</listing>
After that Add routes in your module
Path: appcodeVendorModuleetcadminhtmlroutes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="ordermass" frontName="ordermass">
<module name="Vendor_Module" />
</route>
</router>
</config>
For Invoice Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassInvoice.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassInvoice extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
/**
* @var MagentoSalesModelServiceInvoiceService
*/
protected $_invoiceService;
/**
* @var MagentoFrameworkDBTransaction
*/
protected $_transaction;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoSalesModelServiceInvoiceService $invoiceService,
MagentoFrameworkDBTransaction $transaction,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
$this->_invoiceService = $invoiceService;
$this->_transaction = $transaction;
protected function massAction(AbstractCollection $collection)
$countInvoiceOrder = 0; $NonInvoiceOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canInvoice())
// Create invoice for this order
$invoice = $this->_objectManager->create('MagentoSalesModelServiceInvoiceService')->prepareInvoice($loadedOrder);
//$invoice->getOrder()->setIsInProcess(true);
$invoice->setShippingAmount($loadedOrder->getShippingAmount());
$invoice->setBaseShippingAmount($loadedOrder->getBaseShippingAmount());
$invoice->setTaxAmount($loadedOrder->getTaxAmount());
$invoice->setBaseTaxAmount($loadedOrder->getBaseTaxAmount());
$invoice->setSubtotal($loadedOrder->getSubtotal());
$invoice->setBaseSubtotal($loadedOrder->getBaseSubtotal());
$invoice->setGrandTotal($loadedOrder->getGrandTotal());
$invoice->setBaseGrandTotal($loadedOrder->getBaseGrandTotal());
// Register as invoice item
$invoice->setRequestedCaptureCase(MagentoSalesModelOrderInvoice::CAPTURE_OFFLINE);
$invoice->register();
// Save the invoice to the order
$transaction = $this->_objectManager->create('MagentoFrameworkDBTransaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about invoice #%1. '.$appendusername, $invoice->getId())
)->setIsCustomerNotified(false)->save();
if ($loadedOrder->canShip())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus(MagentoSalesModelOrder::STATE_PROCESSING);
$loadedOrder->addStatusToHistory($loadedOrder->getStatus(), 'Order status set to processing using Mass Invoice action '.$appendusername);
$loadedOrder->save();
$countInvoiceOrder++;
else
if (empty($NonInvoiceOrdernuumbers))
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonInvoiceOrdernuumbers = $NonInvoiceOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonInvoiceOrder = $collection->count() - $countInvoiceOrder;
if ($countNonInvoiceOrder && $countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
elseif ($countNonInvoiceOrder)
$this->messageManager->addError(__('Invoice already created for %1 order(s).', $NonInvoiceOrdernuumbers));
if ($countInvoiceOrder)
$this->messageManager->addSuccess(__('%1 order(s) Invoice created successfully.', $countInvoiceOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
For Shipment Controller
Path: appcodeVendorModuleControllerAdminhtmlOrderMassShip.php
<?php
namespace VendorModuleControllerAdminhtmlOrder;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoUiComponentMassActionFilter;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoSalesApiOrderManagementInterface;
class MassShip extends MagentoSalesControllerAdminhtmlOrderAbstractMassAction
protected $orderManagement;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
OrderManagementInterface $orderManagement,
MagentoBackendModelAuthSession $authSession
)
parent::__construct($context, $filter);
$this->authSession = $authSession;
$this->collectionFactory = $collectionFactory;
$this->orderManagement = $orderManagement;
protected function massAction(AbstractCollection $collection)
$countShipOrder = 0; $NonShipOrdernuumbers = '';
$model = $this->_objectManager->create('MagentoSalesModelOrder');
$username = $this->authSession->getUser()->getUsername();
$appendusername = "(".$username.")";
foreach ($collection->getItems() as $order)
if (!$order->getEntityId())
continue;
$loadedOrder = $model->load($order->getEntityId());
if($loadedOrder->canShip())
$convertOrder = $this->_objectManager->create('MagentoSalesModelConvertOrder');
$shipment = $convertOrder->toShipment($loadedOrder);
// Loop through order items
foreach ($order->getAllItems() AS $orderItem) $orderItem->getIsVirtual())
continue;
$qtyShipped = $orderItem->getQtyToShip();
// Create shipment item with qty
$shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);
// Add shipment item to shipment
$shipment->addItem($shipmentItem);
// Register shipment
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
try
// Save created shipment and order
$shipment->save();
$shipment->getOrder()->save();
//send notification code
$loadedOrder->addStatusHistoryComment(
__('Notified customer about shipment #%1. '.$appendusername, $shipment->getId())
)->setIsCustomerNotified(false)->save();
$itemsCheck = $loadedOrder->getItemsCollection()->addAttributeToSelect('*')->load();
foreach ($itemsCheck as $item) $item->getIsVirtual())
continue;
$item->setQtyShipped($item->getQtyToShip());
$item->save();
$Norder = $shipment->getOrder()->load( $shipment->getOrder()->getId() );
$Norder->save();
// Send email
$this->_objectManager->create('MagentoShippingModelShipmentNotifier')
->notify($shipment);
$shipment->save();
catch (Exception $e)
$this->messageManager->addError(__($e->getMessage()));
if ($loadedOrder->canInvoice())
$loadedOrder->setState(MagentoSalesModelOrder::STATE_PROCESSING, true);
$loadedOrder->setStatus('shipped');
$loadedOrder->addStatusToHistory('shipped', 'Order status set to shipped using Mass Ship action. '.$appendusername);
$loadedOrder->save();
$countShipOrder++;
else
if (empty($NonShipOrdernuumbers))
$NonShipOrdernuumbers = $NonShipOrdernuumbers.$loadedOrder->getIncrementId();
else
$NonShipOrdernuumbers = $NonShipOrdernuumbers.", ".$loadedOrder->getIncrementId();
$countNonShipOrder = $collection->count() - $countShipOrder;
if ($countNonShipOrder && $countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
elseif ($countNonShipOrder)
$this->messageManager->addError(__('Shipment already created for %1 order(s).', $NonShipOrdernuumbers));
if ($countShipOrder)
$this->messageManager->addSuccess(__('%1 order(s) Shipment created successfully.', $countShipOrder));
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($this->getComponentRefererUrl());
return $resultRedirect;
This is tested code, I hope this will help
answered 15 hours ago
Muhammad HashamMuhammad Hasham
2,4621730
2,4621730
1
+1 nice work around
– Prathap Gunasekaran
15 hours ago
Thanks mate @PrathapGunasekaran. Glad you found it useful.
– Muhammad Hasham
15 hours ago
1
Thanks Hasham. Really appreciate your effort on this
– Muhammad Bilal khan
15 hours ago
add a comment |
1
+1 nice work around
– Prathap Gunasekaran
15 hours ago
Thanks mate @PrathapGunasekaran. Glad you found it useful.
– Muhammad Hasham
15 hours ago
1
Thanks Hasham. Really appreciate your effort on this
– Muhammad Bilal khan
15 hours ago
1
1
+1 nice work around
– Prathap Gunasekaran
15 hours ago
+1 nice work around
– Prathap Gunasekaran
15 hours ago
Thanks mate @PrathapGunasekaran. Glad you found it useful.
– Muhammad Hasham
15 hours ago
Thanks mate @PrathapGunasekaran. Glad you found it useful.
– Muhammad Hasham
15 hours ago
1
1
Thanks Hasham. Really appreciate your effort on this
– Muhammad Bilal khan
15 hours ago
Thanks Hasham. Really appreciate your effort on this
– Muhammad Bilal khan
15 hours ago
add a comment |
Muhammad Bilal khan is a new contributor. Be nice, and check out our Code of Conduct.
Muhammad Bilal khan is a new contributor. Be nice, and check out our Code of Conduct.
Muhammad Bilal khan is a new contributor. Be nice, and check out our Code of Conduct.
Muhammad Bilal khan is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f266081%2fcreate-shipment-and-invoice-in-mass-action%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Did you search for any tutorial?
– Shoaib Munir
15 hours ago