[英]Yii2: auto fill fields based on another field from related table
我有一个MySQL表和模型patient_entry
,其中包含字段patient_name
, city
和state
。 我也有另一个表/模型health_card
其中还包含patient_name
, city
和state
。
假设patient_entry
表已经填充了patient_name
, city
和state
。
当我将数据输入health_card
形式,当我选择了patient_name
通过相关下拉字段patient_entry
表,我想相关的city
和state
领域进行自动填充。
我_form.php
对health_card
看起来是这样的:
<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>
在控制器中,我根据建议添加了:
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
]);
}
您所需要的只是调用AJAX
请求来获取所需的字段。 就像下面这样:
(我不知道您的型号名称)查看您的表单,看看您的patient_name
字段的id
是patient_name
。 它通常是modelname-fieldname
。 我假设您的型号名称是Patient
。 因此, patient_name
的id将是patient-patient_name
。
添加ajax请求(在您的视图中)。
调用AJAX的代码如下所示:
$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');
}
});
});");
笔记:
city
state
字段ID具有以下ID: patient-city
state-city
相对。 我没有考虑代码清理的任何条件。 请确保用户数据正确无误。
行动代码:
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
]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.