wil*_*iam 5 yii-extensions typeahead.js yii2
更新已在下面进行
我正在尝试将 Kartik-V Typeahead Basic 小部件与 Yii2 框架一起使用。
下面的代码用于显示所需的数据,用户可以通过大学名称进行搜索,它会出现在自动完成列表中。
问题是,模型需要大学 id,而不是名称。因此,规则是此字段只能存储一个整数,并在您选择预先输入的结果之一后返回验证错误。
<?= $form->field($model, 'university_id')->widget(TypeaheadBasic::classname(), [
'data' => ArrayHelper::map(University::find()->all(),'id','uni_name'),
'pluginOptions' => ['highlight' => true],
'options' => ['placeholder' => 'Filter as you type ...'],
]); ?>
Run Code Online (Sandbox Code Playgroud)
我希望有人可以帮助我了解是否有需要更改的设置,以便在保存时,用户友好的“uni_name”数据会更改回 uni“id”。
更新:由于“Insane Skull”,我的代码部分工作了。
新代码是:
<?= $form->field($model, 'name')->widget(TypeaheadBasic::classname(), [
'data' => ArrayHelper::map(University::find()->all(),'id','uni_name'),
'pluginOptions' => ['highlight' => true],
'options' => ['placeholder' => 'Filter as you type ...', 'id' => 'testID'],
'pluginEvents' => [
'typeahead:select' => new yii\web\JsExpression("function(event, ui) { $('#testing123').val(ui.item.id); }"),
]
]); ?>
<?= Html::activeHiddenInput($model, 'university_id', array ('id' => 'testing123'))?>
Run Code Online (Sandbox Code Playgroud)
现在我不幸收到错误: Method yii\web\JsExpression::__toString() must return a string value
小智 5
我宁愿使用Select2而不是 Typeahead,您基本上是在尝试实现 Select2 上已经存在的功能,但使用 Typeahead。
<?= $form->field($model, 'university_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(University::find()->all(),'id','uni_name'),
'options' => ['placeholder' => 'Filter as you type ...'],
]); ?>
Run Code Online (Sandbox Code Playgroud)