yii применить сортировку к CActiveDataProvider

Я пытаюсь применить сортировку из фильтров запоминания в моей функции администратора.

if (isset($_GET[ucfirst($this->id) .'_sort'])) {            
            $extractSort = $_GET[ucfirst($this->id) .'_sort'];
            //Yii::log($extractSort);
            Yii::app()->user->setState(ucfirst($this->id) .'_sort', $extractSort);
        } else if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
            $_GET['sort'] = Yii::app()->user->getState(ucfirst($this->id) .'_sort');
            //Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
        }

На мой взгляд, у меня есть jquery, который запускает обновление n, чтобы получить состояние модели для другой функции. однако у меня возникли проблемы с применением сортировки.

$model=Yii::app()->user->getState('exportModel');           
            $dataProvider = $model->weeklystatus(array(),false);
            if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
                Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
                $explode  = explode("Yii::app()->user->getState(ucfirst($this->id) .'_sort')" , ".");
                $sort = new CSort();
                $sort->attributes = array(
                        $explode[0]=>array(
                                'asc'=>$explode[0]." ASC",
                                'desc'=>$explode[0] . " DESC",
                        ),
                        '*',
                );  
                $sort->applyOrder($model);
                $dataProvider->setSort($sort);
            }

Моя модельная функция search

public function weeklystatus($arr = array(),$ignore = false,$showspline = false)
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        //Yii::log(var_dump($this->getPlannedPOC()));
        $criteria=new CDbCriteria;
        $criteria->select='*, ((CURDATE() - StartDATE) / (ProjectEndDate - StartDATE ))*100  as PlannedPOC';

        if($showspline)
            $criteria->addCondition('PROJECT = "' .$this->PROJECT . '"');
        else
            $criteria->compare('PROJECT',$this->PROJECT,true);
        $stradd = '';
        if(!empty($arr) && isset($arr['PROJCODE'])){
            $str = '';
            foreach($arr['PROJCODE'] as $value) {
                $str .= "PROJCODE = '$value' || ";
            }           
            $criteria->addCondition(substr($str, 0, -3));
            $stradd .= substr($str, 0, -3);
        }else
            $criteria->compare('PROJCODE',$this->PROJCODE,true);
        $criteria->compare('PROJID',$this->PROJID);
        $criteria->mergeWith($this->dateRangeSearchCriteria('StartDATE', $this->StartDATE));        
        $criteria->mergeWith($this->dateRangeSearchCriteria('ProjectEndDate', $this->ProjectEndDate));
        $criteria->mergeWith($this->dateRangeSearchCriteria('ActualEndDate', $this->ActualEndDate));
        $criteria->mergeWith($this->dateRangeSearchCriteria('ExpectedCompletionDate', $this->ExpectedCompletionDate));
        $criteria->compare('PROCESSOR',$this->PROCESSOR,true);
        if(!empty($arr) && isset($arr['OFFICE'])){
            $stro = '';
            foreach($arr['OFFICE'] as $value) {
                $stro .= "OFFICE = '$value' || ";
            }
            $criteria->addCondition(substr($stro, 0, -3));
            $stradd .= ") AND ( ".substr($stro, 0, -3);
        }else
            $criteria->compare('OFFICE',$this->OFFICE,true);
        $criteria->compare('DEPTCODE',$this->DEPTCODE,true);
        $criteria->compare('PERCENT',$this->PERCENT,true);      
        $criteria->compare('PERCENTPlanned',$this->PERCENTPlanned,true);
        $criteria->compare('KM',$this->KM,true);
        $criteria->compare('KMPlanned',$this->KMPlanned,true);

        if(!empty($arr) && isset($arr['MC'])){
            $str = '';
            foreach($arr['MC'] as $value) {
                $str .= "MC = '$value'";
            }           
            $criteria->addCondition($str);
            if(!empty($stradd)){
                $stradd = "($stradd) AND ($str) AND ";
            }

        }else{
            $criteria->compare('MC',$this->MC,true);
        }
        $criteria->compare('MCSALE',$this->MCSALE);
        $criteria->compare('CATEGORY',$this->CATEGORY,true);
        $criteria->compare('AREA',$this->AREA,true);
        $criteria->compare('COUNTRY',$this->COUNTRY,true);
        $criteria->compare('PROJINFO',$this->PROJINFO,true);
        $criteria->compare('quality_timing',$this->quality_timing,true);
        $criteria->compare('REGION',$this->REGION,true);
        $criteria->compare('ASAAREA',$this->ASAAREA,true);
        $criteria->compare('LORM',$this->LORM,true);

        //$ignore = false;
        //echo "1st: $ignore";
        if(isset($_REQUEST['ViewWebprojectreport'])){
            foreach ($_REQUEST['ViewWebprojectreport'] as $key => $value) {
                //print_r($key);
                //print_r($value);
                if($key != "StartDATE"){
                    if($value != "")
                        $ignore = true;
                }
                //echo "\n";
            }
        }
        //echo "2nd: $ignore";
        if(!$ignore && !$showspline){
            $date = date('Y-m-d',strtotime("-2 week"));
            $criteria->addCondition("StartDATE > '".Yii::app()->params['filterStartDateonReports']."-01-01' AND (PERCENT < 100 || PERCENT is null)");
            //$criteria->addCondition("(PERCENT < 100 || PERCENT is null)");
            //$criteria->addCondition("StartDATE < '$date' AND PERCENT <100 || StartDATE > '$date' AND PERCENT =100 ");
            $criteria->addCondition("$stradd (StartDATE > '$date' AND PERCENT =100) ","OR");
                    /*AND (StartDATE < '$date' AND PERCENT <100)
                    || (StartDATE > '$date' AND PERCENT =100) ");*/
            //$criteria->addCondition("PERCENT < 100 AND StartDATE < '$date'");
            //$criteria->addCondition('StartDATE > '.$date . ' AND PERCENT >  -1' );
        }elseif(!$showspline){
            $criteria->addCondition("StartDATE > '".Yii::app()->params['filterStartDateonReports']."-01-01'");
        }
        /*
        if(isset($_REQUEST['ViewWebprojectreport_sort'])){
            $sort = explode(".",$_REQUEST['ViewWebprojectreport_sort']);
            if(isset($sort[1]))
                $criteria->order = $sort[0] . " " . $sort[1];
            else
                $criteria->order = $_REQUEST['ViewWebprojectreport_sort'];
        }elseif(Yii::app()->user->hasState("ViewWebprojectreport_sort")){
            Yii::log(Yii::app()->user->getState("ViewWebprojectreport_sort"));
            $sort = explode(".",Yii::app()->user->getState("ViewWebprojectreport_sort"));
            if(isset($sort[1]))
                $criteria->order = $sort[0] . " " . $sort[1];
            else
                $criteria->order = Yii::app()->user->getState("ViewWebprojectreport_sort");
        }
            //$criteria->order = 'id desc';
        */

        $sort = new CSort();
        $sort->attributes = array(
                '*', // preserve sorting capability
                "PROJECT"=>array(
                        "asc"=>"PROJECT ASC",
                        "desc"=>"PROJECT DESC"),
                'PlannedPOC'=>array(
                        'asc'=>'PlannedPOC ASC',
                        'desc'=>'PlannedPOC DESC',
                ),
        );


        return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
                "sort"=>$sort,
                'pagination'=>array(
                        'pageSize'=>25,
                ),
        ));
    }

Я пробовал, что не работает

if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {               
                $explode  = explode(".",Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
                $name = $explode[0];
                $sort = new CSort();
                if(count($explode)==2){
                    $sort->attributes = array(
                            /*$name => array(                                   
                                    "desc"=>$name . "DESC"
                            ),*/
                            'defaultOrder'=>array(
                             $name=> CSort::SORT_DESC
                            ),

                    );
                }else{
                    $sort->attributes = array(
                        /*$name => array(
                                "asc"=>$name . " ASC",
                        ),*/
                        'defaultOrder'=>array(
                                $name=> CSort::SORT_ASC
                                ),

                );
                }
                //Yii::log(print_r($explode,true));


                Yii::log(print_r($sort->attributes,true));
                $sort->applyOrder($model);
                $dataProvider->setSort($sort);
            }

следующее распечатывается из CSort

CSort Object
(
    [multiSort] => 
    [modelClass] => ViewWebprojectreport
    [attributes] => Array
        (
        )

    [sortVar] => sort
    [descTag] => desc
    [defaultOrder] => Array
        (
            [PROJECT] => 
        )

    [route] => 
    [separators] => Array
        (
            [0] => -
            [1] => .
        )

    [params] => 
    [_directions:CSort:private] => Array
        (
            [PROJECT] => 
        )

    [_e:CComponent:private] => 
    [_m:CComponent:private] => 
)

person shorif2000    schedule 17.11.2014    source источник


Ответы (1)


Вы бы попробовали:

$model        = Yii::app()->user->getState('exportModel');
$dataProvider = $model->weeklystatus(array(),false);
if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
    Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
    $explode               = explode(Yii::app()->user->getState(ucfirst($this->id) .'_sort'), ".");
    $sort                  = new CSort();
    $sort->attributes      = array(
            $explode[0]    => array(
                    'asc'  => $explode[1] . " ASC",
                    'desc' => $explode[1] . " DESC",
            ),
            '*',
    );  
    $sort->applyOrder($model);
    $dataProvider->setSort($sort);
}
person turutosiya    schedule 18.11.2014
comment
я пробовал это не работает. см. мою функцию поиска модели. - person shorif2000; 18.11.2014