2017-05-29 224 views
0

我有模型包含列cnic,名稱,年齡,城市等 當我想在這裏當用戶開始輸入cnic值,如果該cnic已經在數據庫中,然後完整的cnic值應該出現,並在選擇該值時,名稱,年齡,城市的值自動填入文本輸入。 現在是。Yii2根據從自動完成的選定值填充多字段

$data = Patient::find()->all(); 
    foreach($data as $cnics){ 
     $cnic[] = $cnics->cnic; 
    } 

    echo $form->field($model, 'cnic')->widget(yii\jui\AutoComplete::classname(), [ 
     'clientOptions' => [ 
      'source' => $cnic, 
      'select' => //some code 
], 

<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?> 
<?= $form->field($model, 'age')->textInput(['maxlength' => true]) ?> 
<?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?> 
+0

您可以使用的onchange概念: 這可能會對你有所幫助。 https://stackoverflow.com/questions/31425942/yii2-dropdownlist-onchange-change-autocomplete-widget-source-attribute?rq=1 –

+0

@vijaynathji我讀了鏈接...我的情況是不同的那一個。 –

回答

0
'clientOptions' => [ 
      'source' => $cnic, 
      'select' => new \yii\web\JsExpression("function(event, ui) { 
        var cnic = ui.item.value; 
        complete(cnic); 
      }") 
     ], 

在控制器jQuery代碼

function complete(id){ 

     $.ajax({ 
      url: "?r=patient/autocomplete", 
      type: 'post', 
      data: {cnic: id}, 
      success: function(data) { 

       var obj = JSON.parse(data); 

       $('#patient-name').val(obj[0].name); 
       $('#patient-age').val(obj[0].age); 
       $('#patient-dob').val(obj[0].dob); 
       $('#patient-address').val(obj[0].address); 
       $('#patient-city').val(obj[0].city); 
      } 
     }); 

public function actionAutocomplete() 
{ 
    $cnic = $_POST['cnic']; 
    $query = ModelName::find()->where(['cnic'=> $cnic])->one(); 
    $data[] = ['name' => $query->name,'dob'=> $query->dob, 'age' =>$query->age, 'address'=> $query->address, 'city' => $query->city]; 
    echo json_encode($data); 
} 
相關問題