Yii 框架:从数据库中选择相关记录时如何从数据库中获取 ID
Yii framework: how to get id from DB, when choosing related record from DB
我在网页上有带 Autocomplete::widget
的文本编辑框。
自动完成从数据库填充。当我开始键入并选择自动完成项目(在我的例子中是数据库中的名字)时,我需要从数据库中获取关联的 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',
],
]);
试试这个
<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/
我在网页上有带 Autocomplete::widget
的文本编辑框。
自动完成从数据库填充。当我开始键入并选择自动完成项目(在我的例子中是数据库中的名字)时,我需要从数据库中获取关联的 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',
],
]);
试试这个
<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/