CSV Export

You are viewing revision #7 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 (#8) »

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


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>


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


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";