Yii framework: how to get id from DB, when choosing related record from DB


(Jhd235) #1

could you please advise: I have Yii2. I have text edit box with Autocomplete::widget on the web page. Autocomplete populates from DB. When I start to type and choose Autocomplete item (which is First Name from DB, in my case) I need to get associated id from DB. How could this get implemented?


<?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',

     ],

     ]);    





(Belen) #2

Hi,

You can create a public property, teacherId. In the form is hidden y it will have id of Teacher…

echo AutoComplete::widget([

‘name’ => ‘Teacher’,

‘id’ => ‘ddd’,

‘clientOptions’ => [

‘source’ => $data,

‘autoFill’=>true,

‘minLength’=>’1’,

‘select’ => new JsExpression("function( event, ui ) {

&#036;('#model-teacherId’).val(ui.item.id);

}")],

]);

?>

<?= Html::activeHiddenInput($model, ‘teacherId’)?>