'Magento 2 added custom column in sales order grid but unable to filterable
I have added a product name column in the sale order grid from XML and it shows correctly on the grid but if I use it in filter form it gives the error as "Something went wrong" and the error log has below error
main.CRITICAL: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products' in 'where clause', query was: SELECT COUNT(*) FROM `sales_order_grid` AS `main_table` WHERE (((`products` LIKE '%nato%')))
added below code in sales_order_grid file in custom module
<column name="products" class="Custom\Module\Ui\Component\Listing\Columns\ProductName">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="visible" xsi:type="boolean">true</item>
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Items Name</item>
<item name="disableAction" xsi:type="boolean">true</item>
<item name="sortable" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">3</item>
</item>
</argument>
</column>
Then created UI component column at Custom\Module\Ui\Component\Listing\Columns
class ProductName extends Column
{
protected $_orderRepository;
protected $_searchCriteria;
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
OrderRepositoryInterface $orderRepository,
SearchCriteriaBuilder $criteria,
array $components = [],
array $data = [])
{
$this->_orderRepository = $orderRepository;
$this->_searchCriteria = $criteria;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as &$items) {
$productArr = [];
$order = $this->_orderRepository->get($items["entity_id"]);
foreach ($order->getAllVisibleItems() as $item) {
$productArr[] = $item->getName(); //to get product name
}
$items['products'] = implode(" , " , $productArr);
unset($productArr);
}
}
return $dataSource;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
