Yii框架:从DB中选择相关记录时如何从DB获取id

时间:2018-03-15 09:48:57

标签: yii yii2 yii2-advanced-app yii-extensions yii2-basic-app

我在网页上有Autocomplete::widget的文字编辑框。 自动填充从DB填充。当我开始输入并选择自动完成项目(这是DB中的名字,在我的情况下)我需要从DB获取相关的ID。怎么能实现呢?

<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\Rating;
use app\models\Teacher;
use yii\jui\AutoComplete;
use yii\web\JsExpression;



/* @var $this yii\web\View */
/* @var $model app\models\Rating */
/* @var $form ActiveForm */

    $data = Teacher::find()
    ->select(['lname as value', 'lname as  label','id as id'])
    ->asArray()
    ->all();

    //print_r($data[0].id);//exit;


?>

<div class="rating-input">
ФИО
    <?php 

    echo AutoComplete::widget([
    'name' => 'Teacher',
    'id' =>'ddd',
    'clientOptions' => [
    'source' => $data,
    'autoFill'=>true,
    'minLength'=>'1',
     ],
     ]);    

https://paste.ee/p/BtQav

1 个答案:

答案 0 :(得分:0)

试试这个

  <input type="hidden" name="teacher_id" id="teacher_id" value="">

     <?php 

    echo AutoComplete::widget([
    'name' => 'Teacher',
    'id' =>'ddd',
    'clientOptions' => [
    'source' => $data,
    'autoFill'=>true,
    'minLength'=>'1',
    'select' => new \yii\web\JsExpression("function( event, ui ) {    
                    // $('#teacher_id').val(ui.item.id);//#teacher_id is the id of hiddenInput.
                     console.log(ui.item.id);
                 }")
     ],
     ]);   

您在文档页面中有更多信息:http://www.yiiframework.com/wiki/830/simple-jui-autocomplete-in-yii2/