#StackBounty: #magento2 #uicomponent #product-grid #sales-rule Product grid checkbox input at sales rule form Magento 2 not working

Bounty: 50

I’m using Magento 2.3.4 and want to add product grid with checkbox as an input for sales rule form (shopping cart price rule), i follow the instruction to add product grid input from here but when I print the $_POST value the input data does not exist. Here’s my code:

app/code/Becom/Freegift/Block/Adminhtml/Products/Edit/Tab/Product.php

namespace BecomFreegiftBlockAdminhtmlProductsEditTab;

use MagentoBackendBlockWidgetGrid;
use MagentoBackendBlockWidgetGridColumn;
use MagentoBackendBlockWidgetGridExtended;

class Product extends MagentoBackendBlockWidgetGridExtended
{
    protected $logger;
    /**
     * Core registry
     *
     * @var MagentoFrameworkRegistry
     */
    protected $_coreRegistry = null;

    /**
     * @var MagentoCatalogModelProductFactory
     */
    protected $_productFactory;


    protected $_productCollectionFactory;


    public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoBackendHelperData $backendHelper,
        MagentoCatalogModelProductFactory $productFactory,
        MagentoCatalogModelResourceModelProductCollectionFactory $productCollectionFactory,
        MagentoFrameworkRegistry $coreRegistry,
        BecomFreegiftModelRuleProductFactory $ruleProductFactory,
        array $data = []
    ) {
        $this->_productFactory = $productFactory;
        $this->_coreRegistry = $coreRegistry;
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->ruleProductFactory = $ruleProductFactory;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('catalog_category_products');
        $this->setDefaultSort('entity_id');
        $this->setUseAjax(true);
    }

    /**
     * @return array|null
     */
    public function getItem()
    {
        return $this->_coreRegistry->registry('my_item');
    }

    /**
     * @param Column $column
     * @return $this
     */
    protected function _addColumnFilterToCollection($column)
    {

        // Set custom filter for in category flag
        if ($column->getId() == 'in_category') {
            $productIds = $this->_getSelectedProducts();
            if (empty($productIds)) {
                $productIds = 0;
            }
            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('entity_id', ['in' => $productIds]);
            } elseif (!empty($productIds)) {
                $this->getCollection()->addFieldToFilter('entity_id', ['nin' => $productIds]);
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }
        return $this;
    }

    /**
     * @return Grid
     */
    protected function _prepareCollection()
    {
        // if ($this->getItem()->getId()) {
            // $this->setDefaultFilter(['in_category' => 1]);
        // }
        $collection = $this->_productFactory->create()->getCollection()->setFlag('has_stock_status_filter', true)->addAttributeToSelect(
            'name'
        )->addAttributeToSelect(
            'sku'
        )->addAttributeToSelect(
            'price'
        )->joinField(
          'qty',
          'cataloginventory_stock_item',
          'qty',
          'product_id=entity_id',
          '{{table}}.stock_id=1',
          'left'
        );

        $storeId = (int)$this->getRequest()->getParam('store', 0);
        if ($storeId > 0) {
            $collection->addStoreFilter($storeId);
        }


        $this->setCollection($collection);

        // if ($this->getItem()->getProductsReadonly()) {
        //     $productIds = $this->_getSelectedProducts();
        //     if (empty($productIds)) {
        //         $productIds = 0;
        //     }
        //     $this->getCollection()->addFieldToFilter('entity_id', ['in' => $productIds]);
        // }

        return parent::_prepareCollection();
    }

    /**
     * @return Extended
     */
    protected function _prepareColumns()
    {
        // if (!$this->getItem()->getProductsReadonly()) {
            $this->addColumn(
                'in_category',
                [
                    'type' => 'checkbox',
                    'name' => 'in_category',
                      'values' => $this->_getSelectedProducts(),
                    'index' => 'entity_id',
                    'header_css_class' => 'col-select col-massaction',
                    'column_css_class' => 'col-select col-massaction'
                ]
            );
        // }
        $this->addColumn(
            'entity_id',
            [
                'header' => __('ID'),
                'sortable' => true,
                'index' => 'entity_id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );
        $this->addColumn('name', ['header' => __('Name'), 'index' => 'name']);
        $this->addColumn('sku', ['header' => __('SKU'), 'index' => 'sku']);
        $this->addColumn('qty', ['header' => __('Qty'), 'index' => 'qty']);
        $this->addColumn(
            'price',
            [
                'header' => __('Price'),
                'type' => 'currency',
                'currency_code' => (string)$this->_scopeConfig->getValue(
                    MagentoDirectoryModelCurrency::XML_PATH_CURRENCY_BASE,
                    MagentoStoreModelScopeInterface::SCOPE_STORE
                ),
                'index' => 'price'
            ]
        );
        // $this->addColumn(
        //     'position',
        //     [
        //         'header' => __('Position'),
        //         'type' => 'number',
        //         'index' => 'position',
        //         'editable' => !$this->getItem()->getProductsReadonly()
        //     ]
        // );
        return parent::_prepareColumns();
    }

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

    /**
     * @return array
     */
    protected function _getSelectedProducts()
    {
        $ruleId = $this->getRequest()->getParams('id');
        $products = array();
        if ($ruleId) {
            $vProducts = $this->ruleProductFactory->create()->getCollection()
                                ->addFieldToFilter('rule_id',$ruleId);
            foreach($vProducts as $pdct){
                $products[]  = $pdct->getProductId();
            }
        }
        return $products;
    }

    public function getRowUrl($row)
    {
        return false;
    }
}

app/code/Becom/Freegift/Block/Adminhtml/Products/Edit/FreegiftProducts.php

namespace BecomFreegiftBlockAdminhtmlProductsEdit;

class FreegiftProducts extends MagentoBackendBlockTemplate
{
    /**
     * Block template
     *
     * @var string
     */
    protected $_template = 'products/freegift_products.phtml';

    /**
     * @var MagentoCatalogBlockAdminhtmlCategoryTabProduct
     */
    protected $blockGrid;

    /**
     * @var MagentoFrameworkRegistry
     */
    protected $registry;

    /**
     * @var MagentoFrameworkJsonEncoderInterface
     */
    protected $jsonEncoder;


    protected $_productCollectionFactory;

    /**
     * AssignProducts constructor.
     *
     * @param MagentoBackendBlockTemplateContext $context
     * @param MagentoFrameworkRegistry $registry
     * @param MagentoFrameworkJsonEncoderInterface $jsonEncoder
     * @param array $data
     */
    public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoFrameworkRegistry $registry,
        MagentoFrameworkJsonEncoderInterface $jsonEncoder,
        MagentoCatalogModelResourceModelProductCollectionFactory $productCollectionFactory, //your custom collection
        BecomFreegiftModelRuleProduct $ruleProductFactory,
        array $data = []
    ) {
        $this->registry = $registry;
        $this->jsonEncoder = $jsonEncoder;
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->ruleProductFactory = $ruleProductFactory;
        parent::__construct($context, $data);
    }

    /**
     * Retrieve instance of grid block
     *
     * @return MagentoFrameworkViewElementBlockInterface
     * @throws MagentoFrameworkExceptionLocalizedException
     */
    public function getBlockGrid()
    {

        if (null === $this->blockGrid) {
            $this->blockGrid = $this->getLayout()->createBlock(
                'BecomFreegiftBlockAdminhtmlProductsEditTabProduct',
                'category.product.grid'
            );
        }
        return $this->blockGrid;
    }

    /**
     * Return HTML of grid block
     *
     * @return string
     */
    public function getGridHtml()
    {

        return $this->getBlockGrid()->toHtml();
    }

    /**
     * @return string
     */
    public function getProductsJson()
    {
        $vProducts = $this->_productCollectionFactory->create()
                                ->addFieldToSelect('product_id');
        $products = array();
        foreach($vProducts as $pdct){
            $products[$pdct->getProductId()]  = '';
        }

        if (!empty($products)) {
            return $this->jsonEncoder->encode($products);
        }
        return '{}';
    }

    public function getItem()
    {
        return $this->registry->registry('my_item');
    }
}

app/code/Becom/Freegift/Controller/Adminhtml/Products/Product.php

namespace BecomFreegiftControllerAdminhtmlProducts;


abstract class Product extends MagentoBackendAppAction
{
    /**
     * Authorization level of a basic admin session
     *
     * @see _isAllowed()
     */
    const ADMIN_RESOURCE = 'Becom_Freegift::item_list';


}

app/code/Becom/Freegift/Controller/Adminhtml/Products/Grid.php

namespace BecomFreegiftControllerAdminhtmlProducts;

class Grid extends BecomFreegiftControllerAdminhtmlProductsProduct
{
    /**
     * @var MagentoFrameworkControllerResultRawFactory
     */
    protected $resultRawFactory;

    /**
     * @var MagentoFrameworkViewLayoutFactory
     */
    protected $layoutFactory;

    /**
     * @param MagentoBackendAppActionContext $context
     * @param MagentoFrameworkControllerResultRawFactory $resultRawFactory
     * @param MagentoFrameworkViewLayoutFactory $layoutFactory
     */
    public function __construct(
        MagentoBackendAppActionContext $context,
        MagentoFrameworkControllerResultRawFactory $resultRawFactory,
        MagentoFrameworkViewLayoutFactory $layoutFactory
    ) {
        parent::__construct($context);
        $this->resultRawFactory = $resultRawFactory;
        $this->layoutFactory = $layoutFactory;
    }

    /**
     * Grid Action
     * Display list of products related to current category
     *
     * @return MagentoFrameworkControllerResultRaw
     */
    public function execute()
    {
        // $item = $this->_initItem(true);
        // if (!$item) {
        //     /** @var MagentoBackendModelViewResultRedirect $resultRedirect */
        //     $resultRedirect = $this->resultRedirectFactory->create();
        //     return $resultRedirect->setPath('freegift/item/new', ['_current' => true, 'id' => null]);
        // }
        /** @var MagentoFrameworkControllerResultRaw $resultRaw */
        $resultRaw = $this->resultRawFactory->create();
        return $resultRaw->setContents(
            $this->layoutFactory->create()->createBlock(
                'BecomFreegiftBlockAdminhtmlProductsEditTabProduct',
                'category.product.grid'
            )->toHtml()
        );
    }

    protected function _initItem($getRootInstead = false)
    {
        $id = (int)$this->getRequest()->getParam('id', false);
        // $myModel = $this->_objectManager->create('BecomFreegiftModelRuleProduct');
        //
        // if ($id) {
        //     $myModel->load($id);
        // }
        //
        // $this->_objectManager->get('MagentoFrameworkRegistry')->register('item', $myModel);
        // $this->_objectManager->get('MagentoFrameworkRegistry')->register('my_item', $myModel);
        $this->_objectManager->get('MagentoCmsModelWysiwygConfig');
        return $storeModel;
    }

}

app/code/Becom/Freegift/view/adminhtml/templates/products/freegift_products.phtml

<?php
$blockGrid = $block->getBlockGrid();
$gridJsObjectName = $blockGrid->getJsObjectName();
?>
<?php  echo $block->getGridHtml(); ?>
<input type="hidden" name="category_products" id="in_category_products" data-form-part="sales_rule_form" value="" />
<script type="text/x-magento-init">
    {
        "*": {
            "Becom_Freegift/products/assign-products": {
                "selectedProducts": <?php /* @escapeNotVerified */ echo $block->getProductsJson(); ?>,
                "gridJsObjectName": <?php /* @escapeNotVerified */ echo '"' . $gridJsObjectName . '"' ?: '{}'; ?>
            }
        }
    }
</script>
<!-- @todo remove when "UI components" will support such initialization -->
<script>
    require('mage/apply/main').apply();
</script>

app/code/Becom/Freegift/view/adminhtml/web/products/assign-products.js same as vendor/magento/module-catalog/view/adminhtml/web/catalog/category/assign-products.js


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.