I was trying to create a dynamic form for one of my project. I initialized a ajax request to retrieve value for a field.
<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
'select2:select' => 'function(params) {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url" : "units",
"type" : "post",
"data" : {itemID: itemVal},
success: function (data) {
console.log(data);
console.log(attrID);
$("#reqitems-"+attrID+"-rt_unit").val(data);
},
error: function (errormessage) {
//do something else
alert("not working");
}
});
}',
],
]); ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>
</div>
The ajax is working perfectly in the first index of the dynamic form. But unfortunately from the send index, nothing is happening. I checked couple of questions & answers in stackoverflow for the situation, but everything failed.
Can anyone help me to find a solution?
Hi found a solution in an alternative way using jquery.
Since the elements are dynamically loaded, we need dynamically generate via AJAX or something similar the following input element. I removed the pluginEvent and initialized a new class for dynamic field.
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'reqItem form-control'],
'pluginOptions' => [
'allowClear' => true
]); ?>
Then manually I wrote jquery script to read the element.
<script>
$(document).on("change", ".reqItem", function() {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url": "units",
"type": "post",
"data": {
itemID: itemVal
},
success: function(data) {
console.log(data);
console.log(attrID);
$("#reqitems-" + attrID + "-rt_unit").val(data);
},
error: function(errormessage) {
//do something else
alert("not working");
}
});
});
But still I am working to find the appropriate solution using Yii.