I have a MySQL table and model patient_entry
which contains fields patient_name
, city
and state
. I also have another tabl
All you need is calling an AJAX
request to get needed fields. Just act like below:
(I do not know your model name)take a look at your form and see what is the id
of your patient_name
field. It is usually modelname-fieldname
. I assume that your model name is Patient
. So, the id of patient_name
would be patient-patient_name
.
Add an ajax request (in your view).
The code for calling AJAX could look just like below:
$this->registerJs("$('#patient-patient_name').on('change',function(){
$.ajax({
url: '".yii\helpers\Url::toRoute("controllerName/patient")."',
dataType: 'json',
method: 'GET',
data: {id: $(this).val()},
success: function (data, textStatus, jqXHR) {
$('#patient-city').val(data.city);
$('#patient-state').val(data.state);
},
beforeSend: function (xhr) {
alert('loading!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
});");
Notes:
city
and state
fields has the following id(s): patient-city
and state-city
relatively. I didn't consider any conditions for code cleaning. Please make sure that user data is correct.
Action code:
public function actionPatient($id){
// you may need to check whether the entered ID is valid or not
$model= \app\models\Patient::findOne(['id'=>$id]);
return \yii\helpers\Json::encode([
'city'=>$model->city,
'state'=>$model->state
]);
}