Magento 2 Admin Form: Ui component change grid data based on the selected options via ajax

Smita kagwade
2 min readOct 29, 2020

Hello,

And here I am starting with my first blog.

Many developers face troubles while working with UI grid and form in the admin. Customizing Magento 2 admin with UI components is quite interesting and tricky too, I faced many issues while working with UI components and I dug into it.

I am sharing the steps for changing the grid data on ajax call based on selected values inside the admin form.

Note: The dropdown and the grid are separate fields in the admin form.

the grid is added inside the admin form using the InsertListing component

https://devdocs.magento.com/guides/v2.4/ui_comp_guide/components/ui-insertlisting.html

refer below Screenshot for reference

Grid inside form
  1. add option.js to a form field (in my case for dropdown)
<item name="component" xsi:type="string">Vendor_Module/js/form/element/options</item>

2. Get selected value with event onChange inside js file (options.js)

define([
'underscore',
'uiRegistry',
'Magento_Ui/js/form/element/select',
'Magento_Ui/js/modal/modal'
], function (_, uiRegistry, select, modal) {
'use strict';
return select.extend({
initialize: function (){
this._super();
return this;
},
/**
* On value change handler.
*
*
@param {String} value
*/
onUpdate: function (value) {
require(['jquery', 'reloadGrid'], function ($, reloadGrid) {
reloadGrid.reloadUIComponent("customer_custom_listing.customer_custom_listing_data_source",value);
});
return this._super();
},
});
});

Here we are calling reloader js and passing a listing name (In my case it is customer_custom_listing) and the value of the dropdown field inside the reloadUIComponent function

3.Create componentReloader.js located at web/js folder inside your module

define([
"uiRegistry"
], function (registry) {
'use strict';
return {
reloadUIComponent: function (gridName, value) {
if (gridName) {
var params = [];
var target = registry.get(gridName);
if (target && typeof target === 'object') {
target.set('params.custom_param', value);
}
}
}
};
});

we are setting a custom_param with the value which is passed with the url

4.add config node to your requirejs-config.js

var config = {
map: {
'*': {
reloadGrid: 'Vendor_module/js/componentReloader',
}

5. get the custom_param value inside the data provider class

$customParam= $this->request->getParam('custom_param');

and based on the value of $customParam you can filter your data which will be used by grid

This grid will reload with ajax.

Thank You.

--

--