How to Create Product Grid Serialization in Magento 2
Working the smart way is crucial in business and in Magento 2, you require to be smarter to perform actions quickly!
Whenever you create a custom template and want to apply it to a number of products, you need not do it one by one. I have given the code here to implement product grid serialization in Magento 2. It enables a product grid from where you can select specific products at a time to apply a template or an option.
Steps to Create How to apply Product Grid Serialization in Magento 2
- Create Tabs.php file
12345678910protected function _prepareLayout(){$this->addTab('productgrid',['label' => __('Select Product'),'url' => $this->getUrl('*/*/actionname', ['_current' => true]),'class' => 'ajax',]);} - Create your controller xml file.
1234567891011121314151617<?xml version="1.0"?><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\Extension\Block\Adminhtml\Option\Edit\Tab\Productgrid"name="company.module.edit.tab.productgrid"/><block class="Magento\Backend\Block\Widget\Grid\Serializer" name="productgrid_grid_serializer"><arguments><argument name="input_names" xsi:type="string">products</argument><argument name="grid_block" xsi:type="string">company.module.edit.tab.productgrid</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">products</argument></arguments></block></container></layout> - Controller php action
1234567891011121314151617181920212223242526use Magento\Backend\App\Action\Context;use Magento\Catalog\Controller\Adminhtml\Product\Builder;use Magento\Framework\View\Result\LayoutFactory;use Magento\Catalog\Controller\Adminhtml\Product;class Productgridextends Product{protected $resultLayoutFactory;public function __construct(Context $context,Builder $productBuilder,LayoutFactory $resultLayoutFactory){parent::__construct($context, $productBuilder);$this->resultLayoutFactory = $resultLayoutFactory;}public function execute(){$this->productBuilder->build($this->getRequest());$resultLayout = $this->resultLayoutFactory->create();$resultLayout->getLayout()->getBlock('company.module.edit.tab.productgrid')->setProducts($this->getRequest()->getPost('products', null));return $resultLayout;}} - Create Productgrid.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118<?phpuse Magento\Backend\Block\Template\Context;use Magento\Backend\Helper\Data;use Magento\Catalog\Model\ProductFactory;use Vendor\Extension\Model\OptionFactory;use Magento\Framework\Registry;class Productgridextends\Magento\Backend\Block\Widget\Grid\Extended{protected $coreRegistry = null;protected $productFactory;public function __construct(Context $context,Data $backendHelper,ProductFactory $productFactory,OptionFactory $optionFactory,Registry $coreRegistry,array $data = []){$this->productFactory = $productFactory;$this->optionFactory = $optionFactory;$this->coreRegistry = $coreRegistry;parent::__construct($context, $backendHelper, $data);}protected function _construct() {parent::_construct();$this->setId('product_grid');$this->setDefaultSort('entity_id');$this->setUseAjax(true);}protected function _addColumnFilterToCollection($column){if ($column->getId() == 'products') {$productIds = $this->_getSelectedProducts();if (empty($productIds)) {$productIds = 0;}if ($column->getFilter()->getValue()) {$this->getCollection()->addFieldToFilter('entity_id', ['in' => $productIds]);} else {if ($productIds) {$this->getCollection()->addFieldToFilter('entity_id', ['nin' => $productIds]);}}} else {parent::_addColumnFilterToCollection($column);}return $this;}protected function _prepareCollection() {$collection = $this->productFactory->create()->getCollection()->addAttributeToSelect('*');$this->setCollection($collection);return parent::_prepareCollection();}protected function _prepareColumns(){$this->addColumn('products',['type' => 'checkbox','field_name' => 'products_id[]','required' => true,'values' => $this->_getSelectedProducts(),'align' => 'center','index' => 'entity_id','header_css_class' => 'col-select','column_css_class' => 'col-select']);$this->addColumn('name',['header' => __('Name'),'index' => 'name','header_css_class' => 'col-name','column_css_class' => 'col-name']);$this->addColumn('sku',['header' => __('SKU'),'index' => 'sku','header_css_class' => 'col-sku','column_css_class' => 'col-sku']);return parent::_prepareColumns();}public function getGridUrl(){return $this->_getData('grid_url') ? $this->_getData('grid_url') : $this->getUrl('*/*/productgrid', ['_current' => true]);}protected function _getSelectedProducts(){$products = array_keys($this->getSelectedProducts());return $products;}public function getSelectedProducts(){$tm_id = $this->getRequest()->getParam('id');if (!isset($tm_id)) {$tm_id = 0;}$collection = $this->optionFactory->create()->load($tm_id);$data = $collection->getProducts();$products = explode(',', $data);$proIds = array();foreach ($products as $product) {$proIds[$product] = array('id' => $product);}return $proIds;}}
Follow these steps and save yourself from the tedious tasks!
Hopefully, you’ll find this tutorial helpful. You may ask any doubts regarding the implementation of the code in the comments section below. I’ll be happy to help.
Rate the post with 5 stars if you liked my post 🙂
Happy Coding!
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Hi Sanjay,
I have query product grid coming in our custom module but once we select product and when we goes on to next page without saving , so selected product automatically show unselect.
Please let me know, what we can do that.
Thank you advance
Hello Saurabh,
You might not be getting the data in the _getSelectedProducts function.
You can log and check to find the issue.
Thank you.