Magento – How to save custom grid check box check data in magento 2

customermagento2

create custom module

view/adminhtml/layout/customer_index_edit.xml

<referenceBlock name="customer_form">           
             <block class="vender\module\Block\Adminhtml\Customer\Customerproduct" name="custom_edit_tab_view" />   

            <action method="setTabLabel">
                  <argument name="label" xsi:type="string">Products</argument>
              </action>           

        </referenceBlock>

Now Vender/MOdule/Block/Adminhtml/Customer

<?php
/**
 * @copyright Copyright (c) 2016 www.magebuzz.com
 */
namespace Vender\Module\Block\Adminhtml\Customer;

use Magento\Ui\Component\Layout\Tabs\TabWrapper;
use Magento\Ui\Component\Layout\Tabs\TabInterface; 
use Magento\Customer\Controller\RegistryConstants;
use Magento\Backend\Block\Widget\Form;
use Magento\Backend\Block\Widget\Form\Generic;


class Customerproduct extends Generic implements TabInterface
{

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



    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $_systemStore;
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Store\Model\System\Store $systemStore,

        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        $this->_systemStore = $systemStore;
        parent::__construct($context, $registry, $formFactory, $data);
    }



    /**
     * @return string|null
     */
    public function getCustomerId()
    {
        return $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
    }

    /**
     * @return \Magento\Framework\Phrase
     */ 
    public function getTabLabel()
    {
        return __('Products');
    }


    /**
     * @return \Magento\Framework\Phrase
     */
    public function getTabTitle()
    {
        return __('Products');
    }


    /**
     * @return bool
     */
    public function canShowTab()
    {
        //echo $this->getCustomerId();
        if ($this->getCustomerId()) {
            return true;
        }
        return false;
    }



     /**
     * @return bool
     */
    public function isHidden()
    {
        if ($this->getCustomerId()) {
            return false;
        }
        return true;
    }

    /**
     * Tab class getter
     *
     * @return string
     */
    public function getTabClass()
    {
        return '';
    }


    /**
     * Return URL link to Tab content
     *
     * @return string
     */

    public function getTabUrl()
    {
        return $this->getUrl('module/*/customerproduct', ['_current' => true]);

    }

     /**
     * Tab should be loaded trough Ajax call
     *
     * @return bool
     */

    public function isAjaxLoaded()
    {
        return true;
    }


}

Now
Vender/Module/view/adminhtml/layout/module_index_customerproduct.xml

<?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="Vender\Module\Block\Adminhtml\Product\Edit\Tab\Customerproduct" name="edit.tab.customerproduct"/>
        <block class="Magento\Backend\Block\Widget\Grid\Serializer" name="customerproduct_grid_serializer">
            <arguments>                
                <argument name="grid_block" xsi:type="string">edit.tab.customerproduct</argument>
                <argument name="callback" xsi:type="string">getSelectedProducts</argument>              
                <argument name="input_element_name" xsi:type="string">customerproduct_ids</argument>
                <argument name="reload_param_name" xsi:type="string">contact_products</argument>               
            </arguments>
        </block>
    </container>
</layout>

Vender/Module/view/adminhtml/layout/module_index_customerproductgrid.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="Vender\Module\Block\Adminhtml\Product\Edit\Tab\Customerproduct" name="edit.tab.customerproduct"/>        
    </container>
</layout>

Now Vender/Module/Block/Adminhtml/Product/Edit/Tab

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vender\Module\Block\Adminhtml\Product\Edit\Tab;

use Magento\Backend\Block\Widget\Grid\Column;
use Magento\Backend\Block\Widget\Grid\Extended;



class Customerproduct extends Extended
{

    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @var \Magento\Catalog\Model\Product\LinkFactory
     */
    protected $_linkFactory;

    /**
     * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory]
     */
    protected $_setsFactory;

    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $_productFactory;

    /**
     * @var \Magento\Catalog\Model\Product\Type
     */
    protected $_type;

    /**
     * @var \Magento\Catalog\Model\Product\Attribute\Source\Status
     */
    protected $_status;

    /**
     * @var \Magento\Catalog\Model\Product\Visibility
     */
    protected $_visibility;

    protected $_ScopeConfigInterface;

    protected $_abcproduct;
    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Backend\Helper\Data $backendHelper
     * @param \Magento\Catalog\Model\Product\LinkFactory $linkFactory
     * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $setsFactory
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param \Magento\Catalog\Model\Product\Type $type
     * @param \Magento\Catalog\Model\Product\Attribute\Source\Status $status
     * @param \Magento\Catalog\Model\Product\Visibility $visibility
     * @param \Magento\Framework\Registry $coreRegistry
     * @param array $data
     *
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Magento\Catalog\Model\Product\LinkFactory $linkFactory,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $setsFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory,
        \Magento\Catalog\Model\Product\Type $type,
        \Magento\Catalog\Model\Product\Attribute\Source\Status $status,
        \Magento\Catalog\Model\Product\Visibility $visibility,
        \Magento\Framework\Registry $coreRegistry,
        \Magento\Framework\App\Config\ScopeConfigInterface $ScopeConfigInterface,
        \Vendor\Modulw\Model\AbcproductFactory $abcproduct,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        array $data = []
    ) {
        $this->_linkFactory = $linkFactory;
        $this->_setsFactory = $setsFactory;
        $this->_productFactory = $productFactory;
        $this->_type = $type;
        $this->_status = $status;
        $this->_visibility = $visibility;
        $this->_coreRegistry = $coreRegistry;
        $this->_ScopeConfigInterface = $ScopeConfigInterface;
        $this->_abcproduct= $abcproduct;
        $this->_objectManager = $objectManager;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * _construct
     * @return void
     */
    protected function _construct()
    {

        parent::_construct();
        $this->setId('customerproduct_ids');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setFilterVisibility(true);
        $this->setUseAjax(true);

        //$this->setVarNameFilter('product_filter');

        $this->setUseAjax(true);
        if ($this->getRequest()->getParam('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 = $this->_productFactory->create();
        $collection->addAttributeToSelect('name');
        $collection->addAttributeToSelect('sku');
        $collection->addAttributeToSelect('price');
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }




    /**
     * @return $this
     */
    protected function _prepareColumns()
    {


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


        $this->addColumn(
            'entity_id',
            [
                'header' => __('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('*/*/customerproductgrid', ['_current' => true]);
    }



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

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

    //  print_r($contact->getProducts($contact));

        return  $contact;


    }

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

        return $contact;


    }

    protected function getContact()
    {
        $products = [];
        $customerId = $this->getRequest()->getParam('id');



        if ($customerId) {           

            $contacts = $this->_abcproduct->create()->getCollection();  
            $contacts->addFieldToSelect('*')->addFieldToFilter("customer_id", ['eq' =>$customerId ]);           

        }

         foreach ($contacts as $product) {

            $products[] = $product->getProductId();
        }

        return $products;   


    }


}

http://www.ibnab.com/en/blog/magento-2/magento-2-backend-create-custom-tab-in-customer-view-and-load-grid-inside-admin

Add new tab in customer specific product in customer tab and get all list of product but I can't save,

Because it's not being added in form
How to add checkbox in form and save?

enter image description here

How to save data plz help me

solution
How do i add product grid in customer admin section and save the checkbox values to database

Best Answer

Save class execute method :

public function execute()
{
    $data = $this->getRequest()->getPostValue();

    if ($data) {
        ...
        ...

        $model->setData($data);
        ...
        ...

        try {
            $model->save();
            $this->saveProducts($model, $data);
            ...
    }
    return $resultRedirect->setPath('*/*/');
}

public function saveProducts($model, $post)
{
    // Attach the attachments to contact
    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(\<namespace\<module_name\Model\ResourceModel\<model_name>::TBL_ATT_PRODUCT);
            $insert = array_diff($newProducts, $oldProducts);
            $delete = array_diff($oldProducts, $newProducts);

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

            if ($insert) {
                $data = [];
                foreach ($insert as $product_id) {
                    $data[] = ['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 Item.'));
        }
    }

}

TBL_ATT_PRODUCT will contain your connectivity with product and your table. Hope it will Help You.

Related Topic