gpt4 book ai didi

php - Yii2:根据相关表中的另一个字段自动填充字段

转载 作者:可可西里 更新时间:2023-11-01 07:35:00 25 4
gpt4 key购买 nike

我有一个 MySQL 表和模型 patient_entry,其中包含字段 patient_namecitystate。我还有另一个表/模型 health_card,其中还包含 patient_namecitystate

假设 patient_entry 表已经填充了 patient_namecitystate

当我在 health_card 表单中输入数据时,当我通过与 patient_entry 表相关的下拉字段选择 patient_name 时,我想要相关的 citystate 字段将被自动填充。

health_card_form.php 如下所示:

    <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>

在 Controller 中,我根据建议添加了:

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 请求来获取所需的字段。就像下面这样:

  1. (我不知道你的型号名称)看看你的表格,看看你的 patient_name 字段的 id 是什么。它通常是 modelname-fieldname。我假设您的模型名称是 Patient。因此,patient_name 的 ID 将是 patient-patient_name

  2. 添加一个 ajax 请求(在您的 View 中)。

调用 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');
}
});
});");

注意事项:

  • 将上面代码中的 ControllerName 更改为您自己的。
  • 我假设 citystate 字段的 ID 具有以下 ID:patient-citystate -city 相对。
  • patient 是您 Controller 中的一个 Action
  • 您可能需要删除警报|日志并对上述代码进行一些自定义
  • 我没有考虑代码清理的任何条件。请确保用户数据正确无误。

    1. 最后,将操作代码添加到您的 Controller 中。

Action 代码:

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
]);
}

关于php - Yii2:根据相关表中的另一个字段自动填充字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27212029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com