I've added a new column to the table newsletter_subscriber called "name", now I want to add new grid column with the data from the "name" column.
How can I do it using Event Observers?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityYou can override grid layout file in your custom module. Create a file app/code/Vendor/Module/view/adminhtml/layout/newsletter_subscriber_block.xml
and put below code in it.
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="adminhtml.newslettrer.subscriber.grid.columnSet">
<block class="Magento\Backend\Block\Widget\Grid\Column" name="adminhtml.newslettrer.subscriber.grid.columnSet.name" as="name">
<arguments>
<argument name="header" xsi:type="string" translate="true">Subscriber Name</argument>
<argument name="index" xsi:type="string">name</argument>
<argument name="header_css_class" xsi:type="string">col-name</argument>
<argument name="column_css_class" xsi:type="string">ccol-name</argument>
</arguments>
</block>
</referenceBlock>
</body>
</page>
Also you need to override Resource Model for Grid Collection to make name column searchable.
For this create a file app/code/Vendor/Module/etc/adminhtml/di.xml
and put below code in it.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Newsletter\Model\ResourceModel\Subscriber\Grid\Collection" type="Vendor\Module\Model\ResourceModel\Newsletter\Collection" />
</config>
and create a file app/code/Vendor/Module/Model/ResourceModel/Newsletter/Collection.php
and put below code in it.
<?php
namespace Vendor\Module\Model\ResourceModel\Newsletter;
class Collection extends \Magento\Newsletter\Model\ResourceModel\Subscriber\Collection
{
protected function _initSelect()
{
parent::_initSelect();
$this->showCustomerInfo(true)->addSubscriberTypeField()->showStoreInfo();
$this->_map['fields']['name'] = 'main_table.name';
return $this;
}
}
You need to override below file in your theme or module.
vendor\magento\module-newsletter\view\adminhtml\layout\newsletter_subscriber_block.xml
Then you can add new column with the data from field you created in Table