3

I'm looking for the way to do Grid in Tabs in Magento 2.2.5, I have searched a lot, but almost what I found is from 2016 and so on.

Doesn't match with Magento 2.2.5 anymore.

Ok so what I need to do is look like this.

enter image description here

I'm after this but not working. http://www.codextblog.com/magento-2/how-to-add-custom-grid-into-a-custom-tab-in-product-edit-page-in-magento-2-admin/

EDIT 1:

Here is my ui-component banner_form.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">banner_form.banner_form_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">General Information</item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
    </argument>

    <settings>
        <buttons>
            <button name="save_and_continue" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\SaveAndContinueButton"/>
            <button name="save" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\SaveButton"/>
            <button name="reset" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\ResetButton"/>
            <button name="delete" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\DeleteButton"/>
            <button name="back" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\BackButton"/>
        </buttons>
        <namespace>banner_form</namespace>
        <dataScope>data</dataScope>
        <deps>
            <dep>banner_form.banner_form_data_source</dep>
        </deps>
    </settings>

    <dataSource name="banner_form_data_source">
        <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
        </item>
        </argument>
        <settings>
            <submitUrl path="banner/manage/save"/>
        </settings>
        <dataProvider class="Aht\BannerSlider\Model\Banner\DataProvider" name="banner_form_data_source">
            <settings>
                <requestFieldName>id</requestFieldName>
                <primaryFieldName>id</primaryFieldName>
            </settings>
        </dataProvider>
    </dataSource>

    <fieldset name="general">
        <settings>
            <label/>
        </settings>
        <field name="id" formElement="input">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">banner</item>
                </item>
            </argument>
            <settings>
                <dataType>text</dataType>
                <visible>false</visible>
                <dataScope>id</dataScope>
            </settings>
        </field>
        <field name="name" sortOrder="20" formElement="input">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">banner</item>
                </item>
            </argument>
            <settings>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                </validation>
                <dataType>text</dataType>
                <label translate="true">Banner Name</label>
                <dataScope>name</dataScope>
            </settings>
        </field>
    </fieldset>
</form>

EDIT 2:

I've followed @Rutvee Sojitra solution and get this result.

enter image description here

5

Add this code on your form code where you want to add innerlisting

<insertListing>
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="autoRender" xsi:type="boolean">true</item>
                <item name="ns" xsi:type="string">Name_of_listing_file</item>
            </item>
        </argument>
    </insertListing>

Make your banner_form.xml file like below:
  <?xml version="1.0" encoding="UTF-8"?>

  <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
    <item name="js_config" xsi:type="array">
        <item name="provider" xsi:type="string">banner_form.banner_form_data_source</item>
    </item>
    <item name="label" xsi:type="string" translate="true">General Information</item>
    <item name="template" xsi:type="string">templates/form/collapsible</item>
</argument>

<settings>
    <buttons>
        <button name="save_and_continue" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\SaveAndContinueButton"/>
        <button name="save" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\SaveButton"/>
        <button name="reset" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\ResetButton"/>
        <button name="delete" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\DeleteButton"/>
        <button name="back" class="Aht\BannerSlider\Block\Adminhtml\Banner\Edit\BackButton"/>
    </buttons>
    <namespace>banner_form</namespace>
    <dataScope>data</dataScope>
    <deps>
        <dep>banner_form.banner_form_data_source</dep>
    </deps>
</settings>

<dataSource name="banner_form_data_source">
    <argument name="data" xsi:type="array">
    <item name="js_config" xsi:type="array">
        <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
    </item>
    </argument>
    <settings>
        <submitUrl path="banner/manage/save"/>
    </settings>
    <dataProvider class="Aht\BannerSlider\Model\Banner\DataProvider" name="banner_form_data_source">
        <settings>
            <requestFieldName>id</requestFieldName>
            <primaryFieldName>id</primaryFieldName>
        </settings>
    </dataProvider>
</dataSource>

<fieldset name="general">
    <settings>
        <label/>
    </settings>
    <field name="id" formElement="input">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="source" xsi:type="string">banner</item>
            </item>
        </argument>
        <settings>
            <dataType>text</dataType>
            <visible>false</visible>
            <dataScope>id</dataScope>
        </settings>
    </field>
    <field name="name" sortOrder="20" formElement="input">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="source" xsi:type="string">banner</item>
            </item>
        </argument>
        <settings>
            <validation>
                <rule name="required-entry" xsi:type="boolean">true</rule>
            </validation>
            <dataType>text</dataType>
            <label translate="true">Banner Name</label>
            <dataScope>name</dataScope>
        </settings>
    </field>
</fieldset>
  <fieldset name="banner_information" sortOrder="10">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="label" xsi:type="string">Banner Information</item>
            <item name="collapsible" xsi:type="boolean">false</item>
        </item>
    </argument>
    <insertListing>
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="autoRender" xsi:type="boolean">true</item>
                <item name="ns" xsi:type="string">banner_listing</item>
            </item>
        </argument>
    </insertListing>
</fieldset>

I have added below code:

 <fieldset name="banner_information" sortOrder="10">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="label" xsi:type="string">Banner Information</item>
            <item name="collapsible" xsi:type="boolean">false</item>
        </item>
    </argument>
    <insertListing>
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="autoRender" xsi:type="boolean">true</item>
                <item name="ns" xsi:type="string">banner_listing</item>
            </item>
        </argument>
    </insertListing>
</fieldset>
| improve this answer | |
  • What does this code do? I should put it on the ui-component file? Which is C:\xampp\htdocs\magento\app\code\Aht\BannerSlider\view\adminhtml\ui_component\banner_form.xml ? – fudu Aug 2 '18 at 4:24
  • Yes right add this code in banner_for.xml and if your innerlisting name <item name="ns" xsi:type="string">banner_listing </item> then create banner_listing file – Rutvee Sojitra Aug 2 '18 at 4:26
  • Ohh... I already have banner_listing.xml file, but i dont want to do "grid in tabs" in there, its perfect now. What i need is only "grid in tabs" in banner_form.xml. Hmm .. i'm gonna try it now. Thanks, i will report for you later :) – fudu Aug 2 '18 at 4:30
  • You can accept this answer if you get solution, so it will help to other to reach there solution – Rutvee Sojitra Aug 2 '18 at 5:29
  • I cant put it in my banner_form.xml file, it throw an error : Invalid XML file. Where should i put it? I've tried every where in banner_form.xml :( – fudu Aug 2 '18 at 6:48
1

Below an example using you render the product grid into the tab and save the selected product into the database.

Step - 1 Create The File Vendor\ProductsGrid\Setup\InstallSchema.php

and write the code based on the below file.

<?php
namespace Vendor\ProductsGrid\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface
{
    /**
     * Installs DB schema for a module
     *
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;

        $installer->startSetup();

        if (!$installer->tableExists('vendor_faq')) {
            $table = $installer->getConnection()
                ->newTable($installer->getTable('vendor_faq'))
                ->addColumn(
                    'faq_id',
                    Table::TYPE_INTEGER,
                    10,
                    ['identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true]
                )
                ->addColumn('name', Table::TYPE_TEXT, 255, ['nullable' => false])
                ->addColumn('question', Table::TYPE_TEXT, '2M', ['default' => ''], 'File path')
                ->addColumn('answer', Table::TYPE_TEXT, '2M', ['default' => ''], 'File path')
                ->addColumn('creation_time', Table::TYPE_DATETIME, null, ['nullable' => false], 'Creation Time')
                ->addColumn('update_time', Table::TYPE_DATETIME, null, ['nullable' => false], 'Update Time')
                ->setComment('Sample table');

            $installer->getConnection()->createTable($table);
        }

        if (!$installer->tableExists('vendor_product_attachment_rel')) {
            $table = $installer->getConnection()
                ->newTable($installer->getTable('vendor_product_attachment_rel'))
                ->addColumn('faq_id', Table::TYPE_INTEGER, 10, ['nullable' => false, 'unsigned' => true])
                ->addColumn('product_id', Table::TYPE_INTEGER, 10, ['nullable' => false, 'unsigned' => true], 'Magento Product Id')
                ->addForeignKey(
                    $installer->getFkName(
                        'vendor_faq',
                        'faq_id',
                        'vendor_product_attachment_rel',
                        'faq_id'
                    ),
                    'faq_id',
                    $installer->getTable('vendor_faq'),
                    'faq_id',
                    Table::ACTION_CASCADE
                )
                ->addForeignKey(
                    $installer->getFkName(
                        'vendor_product_attachment_rel',
                        'faq_id',
                        'catalog_product_entity',
                        'entity_id'
                    ),
                    'product_id',
                    $installer->getTable('catalog_product_entity'),
                    'entity_id',
                    Table::ACTION_CASCADE
                )
                ->setComment('Faq Product Attachment relation table');

            $installer->getConnection()->createTable($table);
        }

        $installer->endSetup();
    }
}

2. Step - 2 Now Create the helper Vendor\ProductsGrid\Helper\Data.php

(get products tab Url in admin)

<?php
namespace Vendor\ProductsGrid\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var \Magento\Backend\Model\UrlInterface
     */
    protected $_backendUrl;
    /**
     * @var \Magento\Store\Model\StoreManagerInterface $storeManager
     */
    protected $storeManager;
    /**
     * @param \Magento\Framework\App\Helper\Context   $context
     * @param \Magento\Backend\Model\UrlInterface $backendUrl
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Backend\Model\UrlInterface $backendUrl,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->_backendUrl = $backendUrl;
        $this->storeManager = $storeManager;
    }
    /**
     * get products tab Url in admin
     * @return string
     */
    public function getProductsGridUrl()
    {
        return $this->_backendUrl->getUrl('productsgrid/faq/products', ['_current' => true]);
    }
}

3. Step - 3 Vendor\ProductsGrid\view\adminhtml\layout\productsgrid_faq_edit.xml

Now add the tab product grid into the edit layout as well as below

<action method="addTab">
    <argument name="name" xsi:type="string">attachment_products</argument>
    <argument name="block" xsi:type="array">
        <item name="label" xsi:type="string">Select Products</item>
        <item name="title" xsi:type="string">Select Products</item>
        <item name="url" xsi:type="helper" helper="Vendor\ProductsGrid\Helper\Data::getProductsGridUrl"></item>
        <item name="class" xsi:type="string">ajax</item>
    </argument>
</action>

4. Step - 4 Create Controller Vendor\ProductsGrid\Controller\Adminhtml\Faq\Products.php

<?php

namespace Vendor\ProductsGrid\Controller\Adminhtml\Faq;

use Magento\Backend\App\Action;
use Magento\TestFramework\ErrorLog\Logger;

class Products extends \Magento\Backend\App\Action
{

    /**
     * @var \Magento\Framework\View\Result\LayoutFactory
     */
    protected $_resultLayoutFactory;

    /**
     * @param \Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory
     * @param Action\Context $context
     */
    public function __construct(
        Action\Context $context,
        \Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory
    ) {
        parent::__construct($context);
        $this->_resultLayoutFactory = $resultLayoutFactory;
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return true;
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $resultLayout = $this->_resultLayoutFactory->create();
        $resultLayout->getLayout()->getBlock('productsgrid.edit.tab.products')
                     ->setInProducts($this->getRequest()->getPost('faq_products', null));

        return $resultLayout;
    }
}

5. Step - 5 Create Controller Vendor\ProductsGrid\Controller\Adminhtml\Faq\ProductsGrid.php

<?php

namespace Vendor\ProductsGrid\Controller\Adminhtml\Faq;

use Magento\Backend\App\Action;
use Magento\TestFramework\ErrorLog\Logger;

class ProductsGrid extends \Magento\Backend\App\Action
{

    /**
     * @var \Magento\Framework\View\Result\LayoutFactory
     */
    protected $_resultLayoutFactory;

    /**
     * @param \Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory
     * @param Action\Context $context
     */
    public function __construct(
        Action\Context $context,
        \Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory
    ) {
        parent::__construct($context);
        $this->_resultLayoutFactory = $resultLayoutFactory;
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return true;
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $resultLayout = $this->_resultLayoutFactory->create();
        $resultLayout->getLayout()->getBlock('productsgrid.edit.tab.products')
                     ->setInBanner($this->getRequest()->getPost('faq_products', null));

        return $resultLayout;
    }

}

6. Step - 6 Create Block Vendor\ProductsGrid\Block\Adminhtml\Faq\Edit\Tab\Products.php

<?php

namespace Vendor\ProductsGrid\Block\Adminhtml\Contact\Edit\Tab;

use Vendor\ProductsGrid\Model\FaqFactory;

class Products extends \Magento\Backend\Block\Widget\Grid\Extended
{
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $productCollectionFactory;

    /**
     * 
     *
     * @var faqFactory
     */
    protected $faqFactory;

    /**
     * @var  \Magento\Framework\Registry
     */
    protected $registry;

    protected $_objectManager = null;

 
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        FaqFactory $faqFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    ) {
        $this->faqFactory = $faqFactory;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->_objectManager = $objectManager;
        $this->registry = $registry;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * _construct
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('productsGrid');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        if ($this->getRequest()->getParam('faq_id')) {
            $this->setDefaultFilter(array('in_product' => 1));
        }
    }

    /**
     * add Column Filter To Collection
     */
    protected function _addColumnFilterToCollection($column)
    {
        if ($column->getId() == 'in_product') {
            $productIds = $this->_getSelectedProducts();

            if (empty($productIds)) {
                $productIds = 0;
            }
            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('entity_id', array('in' => $productIds));
            } else {
                if ($productIds) {
                    $this->getCollection()->addFieldToFilter('entity_id', array('nin' => $productIds));
                }
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }

        return $this;
    }

    /**
     * prepare collection
     */
    protected function _prepareCollection()
    {
        $collection = $this->productCollectionFactory->create();
        $collection->addAttributeToSelect('name');
        $collection->addAttributeToSelect('sku');
        $collection->addAttributeToSelect('price');
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    /**
     * @return $this
     */
    protected function _prepareColumns()
    {
        /* @var $model \Vendor\ProductsGrid\Model\Slide */
        $model = $this->_objectManager->get('\Vendor\ProductsGrid\Model\Faq');

        $this->addColumn(
            'in_product',
            [
                'header_css_class' => 'a-center',
                'type' => 'checkbox',
                'name' => 'in_product',
                'align' => 'center',
                'index' => 'entity_id',
                'values' => $this->_getSelectedProducts(),
            ]
        );

        $this->addColumn(
            'entity_id',
            [
                'header' => __('Product ID'),
                'type' => 'number',
                'index' => 'entity_id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id',
            ]
        );
        $this->addColumn(
            'name',
            [
                'header' => __('Name'),
                'index' => 'name',
                'class' => 'xxx',
                'width' => '50px',
            ]
        );
        $this->addColumn(
            'sku',
            [
                'header' => __('Sku'),
                'index' => 'sku',
                'class' => 'xxx',
                'width' => '50px',
            ]
        );
        $this->addColumn(
            'price',
            [
                'header' => __('Price'),
                'type' => 'currency',
                'index' => 'price',
                'width' => '50px',
            ]
        );

        return parent::_prepareColumns();
    }

    /**
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl('*/*/productsgrid', ['_current' => true]);
    }

    /**
     * @param  object $row
     * @return string
     */
    public function getRowUrl($row)
    {
        return '';
    }

    protected function _getSelectedProducts()
    {
        $contact = $this->getContact();
        return $contact->getProducts($contact);
    }

    /**
     * Retrieve selected products
     *
     * @return array
     */
    public function getSelectedProducts()
    {
        $faq = $this->getFaq();
        $selected = $faq->getProducts($faq);

        if (!is_array($selected)) {
            $selected = [];
        }
        return $selected;
    }

    protected function getFaq()
    {
        $contactId = $this->getRequest()->getParam('faq_id');
        $faq   = $this->faqFactory->create();
        if ($faqId) {
            $faq->load($faqId);
        }
        return $faq;
    }

    /**
     * {@inheritdoc}
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isHidden()
    {
        return true;
    }
}

7. Step - 7 Create layout Vendor\ProductsGrid\view\adminhtml\layout\productsgrid_faq_products.xml

<?xml version="1.0" encoding="UTF-8"?>
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
    <container name="root" label="Root">
        <block class="Vendor\ProductsGrid\Block\Adminhtml\Faq\Edit\Tab\Products" name="productsgrid.edit.tab.products"/>
        <block class="Magento\Backend\Block\Widget\Grid\Serializer" name="products_grid_serializer">
            <arguments>
                <argument name="grid_block" xsi:type="string">productsgrid.edit.tab.products</argument>
                <argument name="callback" xsi:type="string">getSelectedProducts</argument>
                <argument name="input_element_name" xsi:type="string">products</argument>
                <argument name="reload_param_name" xsi:type="string">faq_products</argument>
            </arguments>
        </block>
    </container>
</layout>

8. Step - 8 Create layout Vendor\ProductsGrid\view\adminhtml\layout\productsgrid_faq_productsgrid.xml

<?xml version="1.0" encoding="UTF-8"?>
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
    <container name="root" label="Root">
        <block class="Vendor\ProductsGrid\Block\Adminhtml\Faq\Edit\Tab\Products" name="productsgrid.edit.tab.products"/>
    </container>
</layout>

9. Step - 9 Create Save Controller Vendor\ProductsGrid\Controller\Adminhtml\Faq\save.php

<?php

namespace Vendor\ProductsGrid\Controller\Adminhtml\Faq;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\TestFramework\ErrorLog\Logger;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Backend\Helper\Js
     */
    protected $_jsHelper;

    /**
     * @var \Vendor\ProductsGrid\Model\ResourceModel\Faq\CollectionFactory
     */
    protected $_faqCollectionFactory;

    /**
     * \Magento\Backend\Helper\Js $jsHelper
     * @param Action\Context $context
     */
    public function __construct(
        Context $context,
        \Magento\Backend\Helper\Js $jsHelper,
        \Vendor\ProductsGrid\Model\ResourceModel\Faq\CollectionFactory $faqCollectionFactory
    ) {
        $this->_jsHelper = $jsHelper;
        $this->_faqCollectionFactory = $faqCollectionFactory;
        parent::__construct($context);
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return true;
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {

            /** @var \Vendor\ProductsGrid\Model\Faq $model */
            $model = $this->_objectManager->create('Vendor\ProductsGrid\Model\Faq');

            $id = $this->getRequest()->getParam('faq_id');
            if ($id) {
                $model->load($id);
            }

            $model->setData($data);

            try {
                $model->save();
                $this->saveProducts($model, $data);

                $this->messageManager->addSuccess(__('You saved this Faq.'));
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['faq_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\RuntimeException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the Faq.'));
            }

            $this->_getSession()->setFormData($data);
            return $resultRedirect->setPath('*/*/edit', ['faq_id' => $this->getRequest()->getParam('faq_id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }

    public function saveProducts($model, $post)
    {
        
        if (isset($post['products'])) {
            $productIds = $this->_jsHelper->decodeGridSerializedInput($post['products']);
            try {
                $oldProducts = (array) $model->getProducts($model);
                $newProducts = (array) $productIds;

                $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection');
                $connection = $this->_resources->getConnection();

                $table = $this->_resources->getTableName(\Vendor\ProductsGrid\Model\ResourceModel\Faq::TBL_ATT_PRODUCT);
                $insert = array_diff($newProducts, $oldProducts);
                $delete = array_diff($oldProducts, $newProducts);

                if ($delete) {
                    $where = ['faq_id = ?' => (int)$model->getId(), 'product_id IN (?)' => $delete];
                    $connection->delete($table, $where);
                }

                if ($insert) {
                    $data = [];
                    foreach ($insert as $product_id) {
                        $data[] = ['faq_id' => (int)$model->getId(), 'product_id' => (int)$product_id];
                    }
                    $connection->insertMultiple($table, $data);
                }
            } catch (Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the Faq.'));
            }
        }

    }
}

I hope this is helpful to you!!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.