Show shipping amount for entire order in custom report Magento2
-
14-03-2021 - |
Frage
I have created the custom sales report,
used below code in my listing.xml file,
<column name="shipping_amount">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">false</item>
<item name="label" xsi:type="string" translate="true">Shipping Amount</item>
</item>
</argument>
</column>
I am loading the collection from table "sales_order"
This will load the shipping amount column in the Grid,
Here my issue is, I have one order #000000001 which has 3 items,
Sku, 1000, 1001, 1002,
So 3 records are shown in the grid with the shipping amount of 50 for each item which is not correct,
So can we show shipping_amount in the last row of the order record,
is something like that possible?
This is the example pic,
Please anyone suggest me how this can be achieved. Thanks!!
Lösung
I have work around it and able to do as like below.
Vendor/Module/view/adminhtml/ui_component/listing.xml
<column name="shipping_amount_custom" class="Vendor\Module\Ui\Component\Listing\Column\Amount" >
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">false</item>
<item name="label" xsi:type="string" translate="true">Shipping Amount</item>
</item>
</argument>
</column>
Then, Vendor\Module\Ui\Component\Listing\Column\Amount.php
<?php
namespace Vendor\Module\Ui\Component\Listing\Column;
use Magento\CatalogInventory\Model\Stock\StockItemRepository as StockItem;
use Magento\Catalog\Model\Product as Product;
class Amount extends \Magento\Ui\Component\Listing\Columns\Column {
protected $_orderObj;
public function __construct(
\Magento\Framework\View\Element\UiComponent\ContextInterface $context,
\Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = []
){
$this->_orderObj = $orderObj;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource) {
if (isset($dataSource['data']['items'])) {
$connection = $this->getConnection();
foreach ($dataSource['data']['items'] as & $item) {
$productSku = $item['sku'];
$order_id = $item['order_id'];
$lastOrderItemSku = $this->getLastOrderItemDetails($order_id);
if(isset($lastOrderItemSku) && $lastOrderItemSku == $productSku){
$lastItemShippingAmt = $item['shipping_amount'];
}else{
$lastItemShippingAmt = '';
}
$item['shipping_amount_custom'] = $lastItemShippingAmt;
}
}
return $dataSource;
}
public function getLastOrderItemDetails($orderId){
$orders = $this->_orderObj->load($orderId);
$numItems = count($orders->getAllItems());
$i = 0;
foreach ($orders->getAllItems() as $item) {
if(++$i === $numItems) {
$lastItemSku = $item->getSku();
return $lastItemSku;
}
}
return '';
}
}
Hope this will help Others. Cheers!!.