An easy way to use escopes and CActiveDataProvider

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »

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.

MyActiveRecord CActiveRecord class extends { 

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

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!