Yii2: auto fill fields based on another field from related table

前端 未结 1 905
悲&欢浪女
悲&欢浪女 2021-01-13 19:14

I have a MySQL table and model patient_entry which contains fields patient_name, city and state. I also have another tabl

相关标签:
1条回答
  • 2021-01-13 19:46

    All you need is calling an AJAX request to get needed fields. Just act like below:

    1. (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.

    2. 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:

    • Change the ControllerName in above code with your own.
    • I assumed that the id of city and state fields has the following id(s): patient-city and state-city relatively.
    • patient is an action in your controller
    • You may need to remove alerts|logs and do some customization on above code
    • I didn't consider any conditions for code cleaning. Please make sure that user data is correct.

      1. Finally, add action code into your controller.

    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
        ]);
    }
    
    0 讨论(0)
提交回复
热议问题