Sorting a date column in CGridView with CArrayDataProvider

断了今生、忘了曾经 提交于 2019-12-24 16:53:16

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11208678/sorting-a-date-column-in-cgridview-with-carraydataprovider

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!