php – Yii2:根据相关表中的另一个字段自动填充字段
我有一个
MySQL表和模型patient_entry,其中包含字段patient_name,city和state.我还有另一个表/模型health_card,其中还包含patient_name,city和state.
假设patient_entry表已经填充了patient_name,city和state. 当我以health_card格式输入数据时,当我通过与patient_entry表相关的下拉字段选择patient_name时,我希望自动填充相关的城市和州字段. 我的_form.php for health_card看起来像这样: <head> <script> $this->registerJs("$('#healthcard-patient_name').on('change',function(){ $.ajax({ url: '".yiihelpersUrl::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,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= appmodelsPatientEntry::findOne(['id'=>$id]); return yiihelpersJson::encode([ 'city'=>$model->disrict_city,'pin'=>$model->pin_code ]); } 解决方法
您所需要的只是调用AJAX请求来获取所需的字段.就像下面这样:
>(我不知道您的型号名称)查看您的表单,看看您的patient_name字段的id是多少.它通常是modelname-fieldname.我假设您的型号名称是患者.因此,patient_name的id将是patient-patient_name. 调用AJAX的代码如下所示: $this->registerJs("$('#patient-patient_name').on('change',function(){ $.ajax({ url: '".yiihelpersUrl::toRoute("controllerName/patient")."',jqXHR) { $('#patient-city').val(data.city); $('#patient-state').val(data.state); },errorThrown) { console.log('An error occured!'); alert('Error in ajax request'); } }); });"); 笔记: >使用您自己的代码更改上述代码中的ControllerName. >最后,将操作代码添加到控制器中. 行动代码: public function actionPatient($id){ // you may need to check whether the entered ID is valid or not $model= appmodelsPatient::findOne(['id'=>$id]); return yiihelpersJson::encode([ 'city'=>$model->city,'state'=>$model->state ]); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |