An easy way to use escopes and CActiveDataProvider

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

Often used scopes to define criteria in our models. This is a very useful feature as it ensures that in any part of application applying the criteria defined by the scope when called it.

Another common situation is the use CActiveDataProvider which accepts as parameter the model name,a CDbCriteria and a CPagination to construct the ActiveDataProvider.

Eg:

$ DataProvider = new CActiveDataProvider ('Post', array ( 
    'criteria' => array ( 
        'Condition' => 'status = 1' 
        'Order' => 'DESC create_time' 
        'With' => array ('author') 
    ) 
    'pagination' => array ( 
        'PageSize' => 20, 
    ) 
)); 

And if I want to use scopes and simplify a little ...

Extend the class CActiveRecord, creating the file ...protected / components / MyActiveRecord.php.

class MyActiveRecord extends CActiveRecord { 

/ ** 
     * 
     * @ Param Criteria $ CDbCriteria 
     * @ Return CActiveDataProvider 
     * / 
    public function getDataProvider($criteria=null, $pagination=null) {
        if ((is_array ($criteria)) || ($criteria instanceof CDbCriteria) )
           $this->getDbCriteria()->mergeWith($criteria);
        $pagination = CMap:: mergeArray (array ('pageSize' => 10), (array) $pagination); 
        return new CActiveDataProvider(__CLASS__, array(
                        'criteria'=>$this->getDbCriteria(),
                        'pagination' => $pagination
        ));
    }
} 

Edit the model...

class Post extends MyActiveRecord {
...
}

and now we can use our method getDataProvider.

$ DataProvider = Post::model()->with('author')->active()->getDataProvider(); 
... 
$ DataProvider = Post::model()->with('author')->active()->getDataProvider(array('order'=>'create_time DESC')); 
... 
$ DataProvider = Post::model()->with('author')->active()->getDataProvider(array ('order'=>'create_time DESC'), array('pageSize'=>25)); 

That's it!