This post will helpful to implement the ajax request or JS implementation in magento 2 admin form.
Ex: We need to provide City dropdown from admin form, when on selecting the form need to populate Pincode (fetch from DB) and show into next form field called Pincode (Text Field). For that first we have to give onchange option from admin form field. Ex: From add or Edit.php
Sample Code:
add.php
use MyModule\Model\City;
$elements[‘city_id’] = $fieldset->addField(
‘city_id’,
‘select’,
[
‘label’ => __(‘City’),
‘title’ => __(‘City’),
‘name’ => ‘city_id’,
‘required’ => true,
‘class’ => ‘required-entry’,
‘options’ => City::getAllCity(), //In this model will get all city values
]
);
$elements[‘city_id’]->setAfterElementHtml(“
require([‘jquery’,’mage/template’,’jquery/ui’,’mage/translate’],
function($, mageTemplate) {
$(document).ready( function(){
if($(‘select[name=city_id] > option’).length > 0) {
autoPincode(); //Edit
$(‘select[name=city_id]’).change(function(){ //Add
autoPincode();
});
}
function autoPincode(){
if($(‘select[name=city_id] > option’).length > 0) {
var city_id = $(‘select[name=city_id] option:selected’).val();
$.ajax({
url : ‘”. $this->getUrl(”) . “‘,
data: {form_key: window.FORM_KEY,cid: city_id},
type: ‘get’,
dataType: ‘json’,
showLoader:true,
success: function(data){
$(‘#page_pincode’).empty();
$(‘#page_pincode’).append(data.htmlconent);
} }); } } }); }); “);
Controller – city.php
public function execute() {
$cityID = $this->getRequest()->getParam(‘cid’);
$pincodeColl = <Your City Collection>
foreach($pincodeColl as $pinCodeVal){
$state .= $pinCodeVal[‘pincode’];
}
$result[‘htmlconent’] = $state;
$this->getResponse()->representJson($this->_objectManager->get(‘Magento\Framework\Json\Helper\Data’)->jsonEncode($result));
}
This form will work while adding a new field or edit the form. Mean Drop down ajax will work while form load as well as on change both.