首页 > 解决方案 > Yii2- Select2 按钮作为网格视图过滤器不过滤

问题描述

我想在 Yii Grid 视图中使用 Select2 dr 作为过滤器,但它根本不过滤,只刷新页面。

我从 2 个表中获取数据——我只从账户中获取 user_id,从学分中获取其他所有数据。并且每个过滤器都有效,除了“user_id”一个。

<?php

 echo GridView::widget(
     [
         'dataProvider' => $dataProvider,
         'filterModel' => $searchModel,
         'columns' => [
             [
                 'attribute' => 'wp_id',
                 'value' => 'accounts.user_id',
                 'filter' => Select2::widget(
                     [
                         'model' => $searchModel,
                         'attribute' => 'wp_id',
                         'data' => ArrayHelper::map(Accounts::find()->all(), 'wp_id', 'user_id'),
                         'options' => ['placeholder' => ' --Filter by user id-- '],
                         'language' => 'en',
                         'pluginOptions' => [
                             'allowClear' => true,
                         ],
                     ]
                 ),
             ],
         ],
     ]
); ?> 

这是控制器中的操作。

<?php
 public function actionIndex()
    {

        $searchModel = new CreditsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    } ?> 

这就是搜索模型方法

<?php   
public function search($params)
    {
        $query = Credits::find()->with('accounts');

        $dataProvider = new ActiveDataProvider([
            'query' => $query
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }
        if(!empty($this->user_id)) {
            $query->andFilterWhere(['=', 'accounts.user_id', $this->user_id]);
        }
        // grid filtering conditions
        $query->andFilterWhere([
            'user_id' => $this->user_id,
            'wp_id' => $this->wp_id,
            'credits_bought' => $this->credits_bought,
            'purchase_date' => $this->purchase_date,
            'id' => $this->id,
        ]);

        return $dataProvider;
    }
} ?> 

提前致谢!

标签: phpgridviewyii2jquery-select2

解决方案


因为您在过滤器wp_id下传递并从模型中选择作为 select2-dropdown 的值GridViewwp_idAccounts

ArrayHelper::map(Accounts::find()->all(), 'wp_id', 'user_id')

wp_id虽然使用 gridview 列属性并使用 select2 过滤同一列会令人困惑,user_id但如果您想要这样做,您可能需要将上面的内容更改为

ArrayHelper::map(Accounts::find()->all(), 'user_id', 'wp_id')

推荐阅读