How to override CActiveDataProvider Method to show CGridview in descending order by default in Yii

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 07:07:40

问题


I have many models and gridviews in my project and every model has create_dttm field.

I would like now that how can I override class CActiveDataProvider where I'll add DESC Sort condition

i.e.

'sort' => array(
    'defaultOrder' => 'create_dttm DESC',
)

so that it'll work for all my gridviews instead of adding condition in each gridview.

Example:

public function search() {

    $criteria = new CDbCriteria;
    $criteria->compare('id', $this->id);
    $criteria->compare('name', $this->name, true);
    $criteria->compare('age', $this->age);
    $criteria->compare('create_dttm', $this->create_dttm, true);
    $criteria->compare('update_dttm', $this->update_dttm, true);

    return new CActiveDataProvider($this, array(
        'criteria' => $criteria,
        'pagination' => array(
            'pageSize' => 10,
        ),
        'sort' => array(
            'defaultOrder' => 'create_dttm DESC',
        )
    ));
}

How can I deal with this?

Any help would be appreciated.


回答1:


I think the easy way is add the sort variable on each model.

or else you can using this method as below link, but if you using that's way you need change the name as well.

http://www.yiiframework.com/wiki/173/an-easy-way-to-use-escopes-and-cactivedataprovider/

so my suggestion is, add the sort on each model.




回答2:


Have each model inherit from a BaseModel class, and overwrite the default scope method:

<?php
class BaseModel extends CActiveRecord {
...

    public function defaultScope() {
        return array(
            'order' => 'create_dttm DESC',
        );
    }


来源:https://stackoverflow.com/questions/21012384/how-to-override-cactivedataprovider-method-to-show-cgridview-in-descending-order

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