使用数组作为gridview中的排序条件(Yii2)

时间:2017-06-09 08:36:33

标签: sorting gridview yii2

在yii2 gridview表中,我有一个简单的类型数组[1 => car,2 => motobike,3 => ferry]我想用于字母排序(而不是经典关系)。

如何使用数据提供程序进行设置?非常感谢任何帮助!

<?= GridView::widget([
            'dataProvider' => $dataProvider,
        //    'filterModel' => $searchModel,
            'tableOptions' => ['class' => 'table'],
            'layout'=>"{summary}\n<div class='rounded'>{items}</div>\n{pager}",
            'summary' => "Zeige {begin} - {end} von {totalCount} Ideen",
            'columns' => [

                'id',
                [
                    'attribute' => 'art',
                    'value' => function ($model) {
                        $arten = \Yii::$app->params['ideenArten']; //[1=>car, 2=>bike, 3=>scooter etc]
                        return $arten[$model->art];
                    },
                    'label' => 'Kategorie',
                    'filter' => Html::activeDropDownList($searchModel, 'art', \Yii::$app->params['ideenArten'],['class'=>'form-control','prompt' => 'Select Type']),
                ],

            ],
        ]); ?>

我的搜索模型如下:我使用关系成功设置了其他一些字段的排序:

public function search($params)
{
    $query = Idee::find();

    // add conditions that should always apply here
    $query->joinWith(['authorprofile']);


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


    $dataProvider->sort->attributes['authorprofile'] = [
        // The tables are the ones our relation are configured to
        // in my case they are prefixed with "tbl_"
        'asc' => ['user_profile.lastname' => SORT_ASC],
        'desc' => ['user_profile.lastname' => SORT_DESC],
    ];

    $dataProvider->sort->attributes['art'] = [
        'asc' => ['user_profile.lastname' => SORT_ASC],
        'desc' => ['user_profile.lastname' => SORT_DESC],
    ];

    $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;
    }

    // grid filtering conditions
    $query->andFilterWhere([
        'id' => $this->id,
        'art' => $this->art,
        'status' => $this->status,
        'projektstart' => $this->projektstart,
        'projektende' => $this->projektende,
        'created_by' => $this->created_by,
        'updated_by' => $this->updated_by,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,

    ]);

    $query->andFilterWhere(['like', 'title', $this->title])
        ->andFilterWhere(['like', 'body', $this->body])
        ->andFilterWhere(['or',
            ['like', 'user_profile.firstname', $this->authorprofile],
            ['like', 'user_profile.lastname', $this->authorprofile],
        ]);


    return $dataProvider;
}

控制器代码是:

public function actionSpeicher()
{
    $lastIdea = Idee::find()->orderBy("updated_at DESC")->one();
    $searchModel = new IdeeSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

1 个答案:

答案 0 :(得分:0)

1,2,3 ..这些是数据库中数据的表示,因此您的数据库不知道1被称为&#34; car&#34;在你的框架中。你应该将你的类型存储为字符串(这不是一个好主意),或者手动将它们分类(例如1 =&gt; car,2 =&gt; ferry,3 =&gt; motobike)。

但如果你对此不满意,那么你可以解决这样的问题(尽管它很脏而且很慢,我不建议以这种方式实现)

public function search($params)
{
    $query = Idee::find();

    // add conditions that should always apply here
    $query->joinWith(['authorprofile']);

    // ************* GENERATE SQL TABLE FROM arten PHP ARRAY ********************
    // Get your List from params
    $arten = \Yii::$app->params['ideenArten']; // [1=>car, 2=>bike, 3=>scooter etc]
    $artenQuery = null;
    // Convert PHP array to SQL table, pass value (1,2,3) and values (car, boke, scooter)
    foreach ($arten as $key => $value) {
        if(!($artenQuery instanceof \yii\db\Query)) {
            $artenQuery = new \yii\db\Query();
            $artenQuery->select(new \yii\db\Expression("{$key} AS value, \"{$value}\" AS label"));
        } else {
            $artenQuery->union("SELECT {$key} AS value, \"{$value}\" AS label");
        }
    }
    // If you execute $artenQuery itself, you can notice that it will return a table (generated from php array of cource)
    // Then we can leftJoin the table to our main table. Call our temporary arten table as "dummy"
    // Make sure "art" attribute stores number from "arten" list
    $query->leftJoin(['dummy' => $artenQuery], 'dummy.value = art');
    // *************************************************************

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


    // REGISTER SORT FOR RELATIONAL FIELD (joined 'dummy' table, which holds string representative of "art" now)
    $dataProvider->sort->attributes['art'] = [
        'asc' => ['dummy.label' => SORT_ASC],
        'desc' => ['dummy.label' => SORT_DESC],
    ];

    //..... continue your code

我可能会错过您的代码的一些细节。 在我的情况下,我测试了我存储在DB中的状态为0,1,2 ..(并在Web中显示为Deleted,Active,Disabled ..),因此它在字符串代表中工作和排序相当好