Sorting a date column in CGridView with CArrayData

2019-08-04 09:07发布

I'm using a CGridView on a website to display data provided via a CArrayDataProvider. Reason for this is, that the data is cumulated across different tables and enriched with additional computed columns. Sorting and Filtering is generally working fine with this code (... are omitted columns):

$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'produkt-grid',
    'dataProvider'=>new CArrayDataProvider($betroffeneProdukte, array(
            'sort' => array(
                'attributes' => array(
                    'bezeichnung',
                    'datum',
                    ...
                ),
            ),
            'pagination' => false,
        )),
    'enableSorting' => true,
        'columns'=>array(
            array(
                'name'=>'bezeichnung',
                'header'=>'Bezeichnung',
                'value'=>'$data["bezeichnung"]',
            ),
            array(
                'name'=>'datum',
                'header'=>'datum',
                'value'=>'$data["datum"]',
            ),
            ...
        ),

));

Problem is the date column. It is sorting as a string like this (German format): 01.10.2012, 03.08.2012, 10.01.2012, 15.02.2012, ...

I would like to sort it correctly like this of course: 10.01.2012, 15.02.2012, 03.08.2012, 01.10.2012, ...

Anyone got an idea for me?

标签: php yii
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-04 09:32

Thank you for pointing me in the right direction. Actually, the 'datum' column in my example is a string, because I have to use virtual attributes to format dates correctly in German across my application. Now I use the original date-column from the database and format it in the view like this:

array(
  'name'=>'datecolumn',
  'header'=>'Eingangsdatum',
  'value'=>'Yii::app()->dateFormatter->formatDateTime(strtotime($data["datecolumn"]), "medium", null)',
),

=> voila, German display, correctly being able to sort.

查看更多
甜甜的少女心
3楼-- · 2019-08-04 09:38

I think you'll need to send in a raw date / datetime string to your CArrayDataProvider from your data source and then format it with the CGridView instead:

array(
    'name'=>'datum',
    'header'=>'datum',
    'value'=>'$data["datum"]',
    'type'=>'date',
),

It looks like your problem is that Yii thinks your date is a string (instead of a date). If you shift to providing the DataProvider a date, the sorting may work itself out.

查看更多
登录 后发表回答