CSV Export

I needed a csv export function for my cgridview and I wanted to export the entire result set of the sorted and filtered cgridview the user was viewing via ajax.

This reuses the search method so you don't have to rewrite any of your complex criteria or sort code.

I was not using ajaxupdate on the cgridview. IF you are then you need to change the view logic to send those params.

NOTE: Change "searchRailcars" and "TrainCars" for your respective page name and model

View

list($url, $getParams) =   explode("searchRailcars", $_SERVER["REQUEST_URI"]); //will split the url to return all the get params aftert the r param
<a href="<?php echo url('/rip/search/csvRailcars'.$getParams); ?>">CSV Export</a>

MODEL

public function search($pagination = array( 'pageSize'=>20) ){ //edited to set pagination
...
//the criteria and sort logic
...
          return new CActiveDataProvider($this, array('criteria' => $criteria,
                                                      'sort'=>$sort,
                                                      'pagination'=>$pagination
                                        ));
    
} //end func

CONTROLLER

public function actionCsvRailcars(){       
         header('Content-type: text/csv');
         header('Content-Disposition: attachment; filename="centrico-RIP-Railcars-' . date('YmdHi') .'.csv"');
          
         $model=new TrainCars('search');
         $model->unsetAttributes();  // clear any default values
         if(isset($_GET['TrainCars'])) $model->attributes=$_GET['TrainCars'];
         $dataProvider = $model->search(false);
          
         //csv header
         echo TrainCars::model()->getAttributeLabel("beginTime_n").",". TrainCars::model()->getAttributeLabel("endTime_n").",". TrainCars::model()->getAttributeLabel("sequence_n")." \r\n";
      
          foreach ($dataProvider->getData() as $data)
           echo "$data->beginTime_n,$data->endTime_n, $data->sequence_n \r\n";
         }
         exit;      
}