0

我有一个 Gridview 并且在下拉列表中我决定使用 ajax 实现一个 select2 下拉列表,页面加载时间太长,在实现 ajax 后性能提高了很多并且可以正常工作 ajax 搜索。我的问题是当我从列表中选择一个名称时,页面会重新加载并从我选择的那个 id 获取数据,但是在过滤器标题中,它显示 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;
}
4

1 回答 1

1

我知道答案很晚,但我自己遇到了这样的问题。也许该解决方案对某人有用。

为了使值而不是标识符出现,您需要使用 initValueText.

首先,我们需要从选定的标识符中获取用户。

$filteredUserId = ArrayHelper::getValue(Yii::$app->getRequest()->getQueryParam('UserSearch'), 'user_id');
$filteredUser = $filteredUserId ? User::findOne($filteredUserId) : null;

出于某种原因,我的过滤器格式略有不同,可能版本不同或两个选项都有效。我将从我的代码中举一个例子:

[
    'attribute' => 'user_id',                                
    'filterType' => GridView::FILTER_SELECT2,
    'filterWidgetOptions' => [                                   
        'initValueText' => $filteredUser ? $filteredUser->getName() : null,
        'pluginOptions' => [
            'allowClear' => true,
            'closeOnSelect' => true,
            'minimumInputLength' => 1,
            'ajax' => [
                'url' => Url::to(['user/user-list']),
                'dataType' => 'json',
            ],
        ],
    ],
    'filterInputOptions' => ['placeholder' => '...'],
    'value' => function ($model) {
        return $model->user() ? $model->user()->getName() : null;
    },
],
于 2019-12-24T08:29:05.040 回答