I have a MySQL table and model patient_entry
which contains fields patient_name
, city
and state
. I also have another table/model health_card
which also contains patient_name
, city
and state
.
Suppose the patient_entry
table is already filled with patient_name
, city
and state
.
When I am entering data in health_card
form, when I select the patient_name
via drop-down field related to patient_entry
table, I want the related city
and state
fields to be auto-filled.
My _form.php
for health_card
looks like this:
<head>
<script>
$this->registerJs("$('#healthcard-patient_name').on('change',function(){
$.ajax({
url: '".yii\helpers\Url::toRoute("HealthCard/patient")."',
dataType: 'json',
method: 'GET',
data: {id: $(this).val()},
success: function (data, textStatus, jqXHR) {
$('#healthcard-city').val(data.city);
$('#healthcard-pincode').val(data.pin);
},
beforeSend: function (xhr) {
alert('loading!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
});");
</script>
</head>
And in the controller I have added, as per the suggestion, this:
public function actionPatient($id){
// you may need to check whether the entered ID is valid or not
$model= \app\models\PatientEntry::findOne(['id'=>$id]);
return \yii\helpers\Json::encode([
'city'=>$model->disrict_city,
'pin'=>$model->pin_code
]);
}