Skip to content

Instantly share code, notes, and snippets.

@markshust
Created February 24, 2024 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markshust/b351f8ec379a4b18fd564a9463b3ca0e to your computer and use it in GitHub Desktop.
Save markshust/b351f8ec379a4b18fd564a9463b3ca0e to your computer and use it in GitHub Desktop.
Create a custom admin grid collection class to add a custom field to the grid
<?php
// 3. Create a custom collection class that extends SearchResult.
declare(strict_types=1);
namespace Macademy\Minerva\Model\ResourceModel\Faq\Grid;
use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult;
class Collection extends SearchResult
{
protected function _construct(): void
{
$this->_init(
'Macademy\Minerva\Model\Faq',
'Macademy\Minerva\Model\ResourceModel\Faq'
);
}
protected function _initSelect()
{
parent::_initSelect();
// 4. Replace the following line with your custom EAV field/logic.
$this->addFieldToSelect('myfield');
return $this;
}
}
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
+ <!-- 1. Replace the virtualType node with a "type" node, that specifies your new, real collection class.
+
- <virtualType name="Macademy\Minerva\Model\ResourceModel\Faq\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
+ <type name="Macademy\Minerva\Model\ResourceModel\Faq\Grid\Collection">
<arguments>
<argument name="mainTable" xsi:type="string">macademy_minerva_faq</argument>
<argument name="resourceModel" xsi:type="string">Macademy\Minerva\Model\ResourceModel\Faq</argument>
</arguments>
- </virtualType>
+ </type>
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<label translate="true">Question</label>
</settings>
</column>
+ <!-- 2. Add the name and label for your new custom field. -->
+
+ <column name="myfield">
+ <settings>
+ <label translate="true">My Field</label>
+ </settings>
+ </column>
</columns>
</listing>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment