1

I have created one UI form with UI grid. When I get params in controller I can not get selected row of UI grid. How to do that?

Here is my UI Component layout file.

<fieldset name="other_field">    
    <field name="1">
    </field>
    <field name="2">
    </field>
    <field name="3">
    </field>
</fieldset>
<fieldset name="slider_config">
        <argument name="data" xsi:type="array">
             <item name="config" xsi:type="array">
             <item name="collapsible" xsi:type="boolean">true</item>
             <item name="label" xsi:type="string" translate="true">Add Slides to Slider</item>
             <item name="sortOrder" xsi:type="number">21</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">vendor_module_slide_listing</item>
                   </item>
             </argument>
        </insertListing>
</fieldset>   

In above code i need selected rows of insertListing in controller file.

1

For that, create phtml file in adminhtml for add selected product ids in hidden field and pass into js.

Follow this below steps :

1) Create this phtml file in your adminhtml templates

/app/code/Vendor/Module/view/adminhtml/templates/slides.phtml

<?php
$blockGrid = $block->getBlockGrid();
$gridJsObjectName = $blockGrid->getJsObjectName();

?>
<?= $block->getGridHtml() ?>
<input type="hidden" name="slides" data-form-part="product_form" id="slides" value=""  />
<script type="text/x-magento-init">
    {
        "*": {
            "SIT_ProductFaqNew/js/assign-faq": {
                "selectedProducts":  <?= /* @escapeNotVerified */ $block->getProductsJson() ?>,
                "gridJsObjectName": <?= /* @escapeNotVerified */ '"' . $gridJsObjectName . '"' ?: '{}' ?>
            }
        }
    }
</script>
<script>
    require('mage/apply/main').apply();
</script>

2) Add code of getProductsJson() function in block file of product grid.

/app/code/Vendor/Module/Block/Adminhtml/AssignSlides.php

<?php

namespace Vendor\Module\Block\Adminhtml;

use Magento\Backend\Block\Template;

class AssignSlides extends Template {
    /**
     * Block template
     *
     * @var string
     */
    protected $_template = 'assign_slides.phtml';

    protected $yourCollectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Json\EncoderInterface $jsonEncoder,
        \Vendor\Module\Model\SlidesFactory $yourCollectionFactory,
        array $data = []
    ) {
        $this->registry = $registry;
        $this->jsonEncoder = $jsonEncoder;
        $this->yourCollectionFactory = $yourCollectionFactory;
        parent::__construct($context, $data);
    }

    /**
     * @return string
     */
    public function getProductsJson() {

        $entity_id = $this->getRequest()->getParam('entity_id');

        $yourCollectionFactory = $this->yourCollectionFactory->create()->load($entity_id);

        if (isset($yourCollectionFactory)) {
            $result = $yourCollectionFactory['slides'];
            $result = explode(',', $result);
            return $this->jsonEncoder->encode($result);
        }
        return '{}';
    }
}

3) Assign json value in your hidden field in this js file :

/app/code/Vendor/Module/view/adminhtml/web/js/assign-products.js

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/* global $, $H */

define([
    'mage/adminhtml/grid'
], function () {
    'use strict';

    return function (config) {
        var selectedProducts = config.selectedProducts,
            categoryProducts = $H(selectedProducts),
            gridJsObject = window[config.gridJsObjectName],
            tabIndex = 1000;
        /**
         * Show selected product when edit form in associated product grid
         */
        $('slides').value = Object.toJSON(categoryProducts); // add your hidden field id
        /**
         * Register Category Product
         *
         * @param {Object} grid
         * @param {Object} element
         * @param {Boolean} checked
         */
        function registerCategoryProduct(grid, element, checked) {
            if (checked) {
                if (element.positionElement) {
                    element.positionElement.disabled = false;
                    categoryProducts.set(element.value, element.positionElement.value);
                }
            } else {
                if (element.positionElement) {
                    element.positionElement.disabled = true;
                }
                categoryProducts.unset(element.value);
            }
            $('slides').value = Object.toJSON(categoryProducts); // add your hidden field id
            grid.reloadParams = {
                'selected_products[]': categoryProducts.keys()
            };
        }

        /**
         * Click on product row
         *
         * @param {Object} grid
         * @param {String} event
         */
        function categoryProductRowClick(grid, event) {
            var trElement = Event.findElement(event, 'tr'),
                isInput = Event.element(event).tagName === 'INPUT',
                checked = false,
                checkbox = null;

            if (trElement) {
                checkbox = Element.getElementsBySelector(trElement, 'input');

                if (checkbox[0]) {
                    checked = isInput ? checkbox[0].checked : !checkbox[0].checked;
                    gridJsObject.setCheckboxChecked(checkbox[0], checked);
                }
            }
        }

        /**
         * Change product position
         *
         * @param {String} event
         */
        function positionChange(event) {
            var element = Event.element(event);

            if (element && element.checkboxElement && element.checkboxElement.checked) {
                categoryProducts.set(element.checkboxElement.value, element.value);
                $('slides').value = Object.toJSON(categoryProducts); // add your hidden field id
            }
        }

        /**
         * Initialize category product row
         *
         * @param {Object} grid
         * @param {String} row
         */
        function categoryProductRowInit(grid, row) {
            var checkbox = $(row).getElementsByClassName('checkbox')[0],
                position = $(row).getElementsByClassName('input-text')[0];

            if (checkbox && position) {
                checkbox.positionElement = position;
                position.checkboxElement = checkbox;
                position.disabled = !checkbox.checked;
                position.tabIndex = tabIndex++;
                Event.observe(position, 'keyup', positionChange);
            }
        }

        gridJsObject.rowClickCallback = categoryProductRowClick;
        gridJsObject.initRowCallback = categoryProductRowInit;
        gridJsObject.checkboxCheckCallback = registerCategoryProduct;

        if (gridJsObject.rows) {
            gridJsObject.rows.each(function (row) {
                categoryProductRowInit(gridJsObject, row);
            });
        }
    };
});
| 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.