我有一个 Gridview 并且在下拉列表中我决定使用 ajax 实现一个 select2 下拉列表,页面加载时间太长,在实现 ajax 后性能提高了很多并且可以正常工作 ajax 搜索。我的问题是当我从列表中选择一个名称时,页面会重新加载并从我选择的那个 id 获取数据,但是在过滤器标题中,它显示 id 而不是显示名称。下面的代码仅适用于用户,但组织和消息的列也有同样的问题。
查看/index.php
$formatJs = <<< 'JS'
var id_user = function (id_user) {
return id_user.id ? id_user.id : id_user.text;
}
JS;
$this->registerJs($formatJs, \yii\web\View::POS_HEAD);
...
[
'attribute' => 'id_user',
'label' => Yii::t("app", "User"),
'value' => function ($model) {
return Notification::findOne($model->id)->idUser->name;
},
'filterType' => GridView::FILTER_SELECT2,
'filterWidgetOptions' => ['options' => ['placeholder' => ''], 'pluginOptions' => ['allowClear' => true, 'minimumInputLength' => 3,
'ajax' => [
'url' => Url::to(['user-list']),
'dataType' => 'json',
'data' => new JsExpression('function(params){return{q:params.term};}'),
'cache' => true,
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateSelection' => new JsExpression('id_user'),]
],
],
控制器.php
public function actionUserList($q = null, $id = null) {
Yii::$app->response->format = Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select('id, name AS text')->from('tbl_user')->where(['like', 'name', $q])->limit(10);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
} elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => User::find($id)->name];
}
return $out;
}