paolo@bimodesign.com | +34 608 61 64 10

Framework

        

Yii, how to add a button for CSV reports

In order to add a button to generate, for example, a CSV reports (or any tasks), you could make these steps.
We suppose that we have just created a menu "Customer" and we could here a button and a html select with several differents CSV reports.

Modify the /view/customer/admin.php
You have to add this PHP code at the end

echo CHtml::dropDownList('type', 1, array(
    'usuarioactivosmesactual'=>'Usuario Activos Mes Actual',
    ventasmesactual'=>'Ventas Mes Actual'));

Now, you need to add the reference of this button, so you have to add this code

Yii::app()->clientScript->registerScript('reports', "
   $('#informes-button').on('click',function() {
         var typereports = $('#type').val()
         window.location = '". $this->createUrl('reports')  . "?type='+typereports;
   });
");

You can see that we define a new controller called "reports" and we pass it the "type"

Modify the /controllers/CustomerControllers.php
You need to add a new action actionReports, with this code (we suppose we have only two reports):

public function actionInformes()
{
    $fp = fopen('php://temp', 'w');

    /* 
    * Write a header of csv file
    */
           
    switch ($_GET['type']) {
        case "usuarios":
            $headers = array('NOMBREAPELLIDO',
                            'CORREO',
                            'CODIGOPADRE',
                            'CODIGOUSUARIO');

            $row = array();

            foreach($headers as $header) {
	            $row[] = Customer::model()->getAttributeLabel($header);
            }
            fputcsv($fp,$row);
                        
            $sqlReport=" SELECT CONCAT(firstname,' ',lastname) AS NOMBREAPELLIDO,
                                email AS CORREO,
                                codepromopadre AS CODIGOPADRE,
                                codepromouser AS CODIGOUSUARIO
                           FROM customer
                       ORDER BY NOMBREAPELLIDO";
            break;

        case "usuarioscreditos":
            $headers = array('NOMBREAPELLIDO',
                            'CORREO',
                            'TOTALPERSONAL',
                            'TOTALNETWORK');

            $row = array();

            foreach($headers as $header) {
                $row[] = Customer::model()->getAttributeLabel($header);
            }
            fputcsv($fp,$row);
                        
            $sqlReport=" SELECT CONCAT(customer.firstname,' ',customer.lastname) AS NOMBREAPELLIDO,
                                customer.email AS CORREO,
                                credit.total_personal AS TOTALPERSONAL,
                                credit.total_network AS TOTALNETWORK                                            
                           FROM customer 
                      LEFT JOIN credit ON credit.id_customer=customer.id_customer
                       ORDER BY NOMBREAPELLIDO ";

            break;                    
    }
            
    $models= Yii::app()->db->createCommand($sqlReport)->queryAll();
                       
    foreach($models as $item){
        $row=array();
                
        switch ($_GET['type']) {
            case "usuarios":
                $row[]=$item['NOMBREAPELLIDO'];
                $row[]=$item['CORREO'];
                $row[]=$item['CODIGOPADRE'];
                $row[]=$item['CODIGOUSUARIO'];
            break;    

            case "usuarioscreditos":
                $row[]=$item['NOMBREAPELLIDO'];
                $row[]=$item['CORREO'];
                $row[]=$item['TOTALPERSONAL'];
                $row[]=$item['TOTALNETWORK'];
            break;
        }
                
 	   fputcsv($fp,$row);
    }
    
    /*
    * save csv content to a Session
    */
    rewind($fp);
    Yii::app()->user->setState('reports',stream_get_contents($fp));
    fclose($fp);
            
    Yii::app()->request->sendFile('reports.csv',Yii::app()->user->getState('informes'));
    Yii::app()->user->clearState('reports');
}	

Note: this code will produce always the file reports.csv, but, of course, you could dedice to custom its name.
You have to assign the permissions to this action, so you have to modify this code line, on the accessRules methods in this way

array('allow', // allow authenticated user to perform 'create' and 'update' actions
      'actions'=>array('create','update','export','reports'),
      'users'=>array('@'),
),

Note: For all the new actions that you create into the Customer section, you have to assign the permissions.