HOW TO export CGridView results to CSV file?

Discuss everything related to ApPHP Durecty CMF. All versions. Any questions related to the Directy CMF developing or using should be posted to this forum.

Moderators: alexandrleonenko, alexmst

administrator
Site Admin
Site Admin
Posts: 6169
Joined: Jan 7th, '09, 23:18
Contact:

HOW TO export CGridView results to CSV file?

Postby administrator » Apr 10th, '17, 12:38

To implement export feature you have to perform 3 simple steps:

1. Add Export button in view file:

Code: Select all

echo '<a href="listings/export" class="export-data align-right"><b class="icon-export">&nbsp;</b> '.A::t('directory', 'Export').'</a>';


2. Create "export" action in yuor controller:

Code: Select all

/**
 * Export data action handler
 */
public function exportAction()
{
   Website::setBackend();
   Website::prepareBackendAction('edit', 'directory', 'listings/manage');

   $filename = 'listings.csv';
   $output = "\xEF\xBB\xBF";
   
   $listings = Listings::model()->findAll();
   $headersCount = 0;
   foreach($listings as $listing){
      $fieldsCount = 0;
      
      // Prepare headers
      if(!$headersCount){
         foreach($listing as $key => $val){
            if($headersCount++) $output .= ',';
            $output .= ucwords(str_replace('_', ' ', $key));
         }
         $output .= "\n";
      }
      
      // Prepare records
      foreach($listing as $key => $val){
         if($fieldsCount++) $output .= ',';
         $output .= '"'.$val.'"';
      }
      $output .= "\n";
   }
   
   try{
      A::app()->getRequest()->downloadFile($filename, $output, 'application/csv');         
   }catch(Exception $e){
      $this->_view->errorHeader = A::t('directory', 'Export Error');
      $this->_view->errorText = CWidget::create(
         'CMessage', array('error', A::t('directory', 'An error occurred while exporting operation! Please try again later.'))
      );
      $this->_view->render('listings/export');
   }       
}


3. Create "export" view file (for errors):

Code: Select all

<?php
    $this->_activeMenu = 'listings/manage';
    $this->_breadCrumbs = array(
        array('label'=>A::t('directory', 'Modules'), 'url'=>'modules/'),
        array('label'=>A::t('directory', 'Business Directory'), 'url'=>'modules/settings/code/directory'),
        array('label'=>A::t('directory', 'Listings Management'), 'url'=>'listings/manage'),
    );
?>

<h1><?= A::t('directory', 'Listings Management'); ?></h1>
<div class="bloc">
    <div class="sub-title">
        <?= $errorHeader; ?>       
        <a href="listings/manage" class="back-link"><?= A::t('directory', 'Back'); ?></a>
    </div>   
    <div class="content">
        <p style="text-align:center;"><?= $errorText; ?></p>
    </div>
</div>

Return to “ApPHP Directy CMF {developers/users}”