Yii2 GridView SqlDataprovider排序不起作用

时间:2017-02-13 10:13:03

标签: php gridview yii2

我有以下查询:

$query = (new \yii\db\Query())
            ->select([
                'p.id',
                'p.name',
                'c.name AS contact_name',
                'l.name AS laboratory',
                'p.status',
                'p.address',
                'p.start_date',
                'p.city',
                'p.updated_at',
                'stortbon.attribute_value as Stortbon',
                'vrijgave.attribute_value as Vrijgave'
            ])
            ->from(['project p'])
            ->innerJoin('contact c', 'p.contact_id = c.id')
            ->innerJoin('contact l', 'p.contact_id = l.id')
            ->innerJoin(['stortbon' => $stortbon_query], 'p.id = stortbon.model_id')
            ->innerJoin(['vrijgave' => $vrijgave_query], 'p.id = vrijgave.model_id');

我正在使用SqlDataprovider在Gridview中获取结果:

$dataProvider = new SqlDataProvider([
        'sql' => $query->createCommand()->sql,
        'totalCount' => $query->count(),
        'key'        => 'id',
        'sort' => [
            'attributes' => [
                'start_date' => [
                    'asc' => ['start_date' => SORT_ASC],
                    'desc' => ['start_date' => SORT_DESC],
                    'default' => SORT_DESC,
                    'label' => 'Start Datum',
                ],
            ],
        ],
    ]);

gridview和columns:

            $columns[] = [
                    'header' => Yii::t('project', 'Start date'),
                    'attribute' => 'start_date',
                    'format' => 'date',
                    'filter' => false,
                ];

GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel'  => $searchModel,
            'columns'      => $columns,
        ]); 

我也尝试将名称更改为p.start_date但它显示的是gridview但不显示排序按钮/标题链接以对数据进行降序或升序排序

1 个答案:

答案 0 :(得分:2)

在Gridview小部件中删除过滤器模型,因为您无法将sqldataprovider与searchmodel组合

GridView::widget([
    'dataProvider' => $dataProvider,
    'columns'      => $columns,
]); 

和在网格列中的sqldataprovider中提供短路 你必须在短数组中声明

$dataProvider = new SqlDataProvider([
    'sql' => $query->createCommand()->sql,
    'totalCount' => $query->count(),
    'key'        => 'id',
    'sort' => [
        'defaultOrder' => ['start_date'=>SORT_DESC],
        'attributes' => [
            'start_date',
            'status',
            'address',
            ],
        ],
    ],
]);