Magento 2 : Custom column filter with serialize data in UI grid
Pergunta
I added product name column in my module ui grid. In my database, it's save product id.
I display successfully product name in column by product id. But, filter not working when I search by product name.
I just want to add custom field in collection when I do filter.
Current grid collection array :
Array
(
[0] => Array
(
[id] => 1
[rule_title] => {"1":"Rule 1","2":"Rule 1"}
[status] => 1
)
[1] => Array
(
[id] => 2
[rule_title] => {"1":"Rule 2","2":"Rule 2"}
[status] => 1
)
)
Want array like this :
Array
(
[0] => Array
(
[id] => 1
[rule_title] => {"1":"Rule 1","2":"Rule 1"}
[status] => 1
[rule_name] => Rule 1
)
[1] => Array
(
[id] => 2
[rule_title] => {"1":"Rule 2","2":"Rule 2"}
[status] => 1
[rule_name] => Rule 2
)
)
How to do that?
Any help would be appreciated !!
Thanks.
Solução
I also face same issue and solved by this below code :
app/code/Vendor/Module/Model/ResourceModel/Page/Grid/Collection.php
protected function _renderFiltersBefore() {
$filters = $this->request->getParam('filters');
if (isset($filters['your_field'])) {
$match = sprintf('%%%s%%', substr($this->serializer->serialize(['your key' => $filters['your_field']]), 1, -1));
$this->addFieldToFilter('your_field', ['like' => $match]);
}
parent::_renderFiltersBefore();
}
You need to inject this below class in your construct of Collection.php file
\Magento\Framework\App\RequestInterface $request
\Magento\Framework\Serialize\Serializer\Json $serializer
Your data is like :
{"1":"Rule 1","2":"Rule 1"}
Then, you can do like this
$match = sprintf('%%%s%%', substr($this->serializer->serialize(['1' => "Rule 1"]), 1, -1));
Hope, It will helpful for you.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange