Yii Framework Forum

Print gridview search in PDF using kartik-mPDF extension [solved]


(Juan Carlos Reyes Suazo) #1

Hey folks, I need help again. Im using kartik-mpdf library to generate pdf’s of my gridviews, the thing is I want to pass $dataProvider and $searchModel from index.php to the view that is going to be renderer as pdf document (pdf.php), So, when I search on index and click the button ‘Generar pdf’ it calls action GenerarPdf on AlumnoController and loads the same $searchModel and $dataProvider of index action into pdf.php gridview and generate the pdf file.

Here’s the code.
AlumnoController.php - actionGenerarPdf

public function actionGenerarPdf($searchModel, $dataProvider) 
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
        $formatter = \Yii::$app->formatter;
        $pdf = new Pdf([
            'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
            'destination' => Pdf::DEST_BROWSER,
            //Se renderiza la vista "pdf" (que abrirá la nueva ventana)
            'content' => $this->renderPartial('pdf', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
                ]),
            'options' => [
            // any mpdf options you wish to set
            ],
            'methods' => [
                'SetTitle' => 'SIE: Sistema de Informacion Estudiantil',
                'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
                'SetHeader' => ['SIE: Sistema de Información Estudiantil||Generado el: ' . $formatter->asDate(date("r"))],
                'SetFooter' => ['|Página {PAGENO}|'],
                'SetAuthor' => 'SIE: Sistema de información Estudiantil',
                'SetCreator' => 'Juan Carlos Reyes Suazo',
//              'SetKeywords' => 'Sie, Yii2, Export, PDF, MPDF, Output, yii2-mpdf',
            ]
        ]);
        return $pdf->render();
    }

index.php

<p>
        <?php 
            if (User::isSuperAdmin(Yii::$app->user->identity->id)){
                echo Html::a('Crear Alumno', ['create'], ['class' => 'btn btn-success']); 
                echo Html::a('Ver PDF', [
                    '/alumno/generar-pdf', 
                    'searchModel' => $searchModel, 
                    'dataProvider' => $dataProvider
                        ], 
                        [
                    'class' => 'btn btn-success', 
                    'target'=>'_blank', 
                    'data-toggle'=>'tooltip', 
//    'title'=>'Will open the generated PDF file in a new window'
                ]);
            }
        ?>
    </p>

pdf.php

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            //'id',
            ['attribute' => 'nombre',
             'format' => 'raw',
             'value'=>function ($data) {
                        return Html::a($data['nombre'],['alumno/view', 'id' => $data['id']]);
                      },
             ],
            //'rut',
            ['attribute' => 'curso_id',
             'format' => 'raw',
             'value'=>function ($data) {
                        return Html::a($data['curso_id'],['curso/view', 'id' => $data['curso_id']]);
                      },
             ],
            //'fecha_nacimiento',
            //'fono',
            //'direccion',
            //'email:email',
            //'apoderado',
            ['attribute' => 'apoderado',
             'format' => 'raw',
             'value'=>function ($data) {
                          if ($data->apoderado_id != null)
                              return Html::a($data->apoderado->nombre, ['apoderado/view', 'id' => $data['apoderado_id']]);
                          else
                              return null;
                        
                      },
             ],
            //'apoderado_suplente',
            //'fono_apoderado',
            //'fono_apoderado_sup',
            //'antecedentes_medicos',
            //'grupo_sanguineo',
            //'programa_integracion',
            //'taller_artistico',
            //'anotaciones',

            ['class' => ActionColumn::className(), 'template' => '{update} {delete}'],
        ],
    ]); ?>

Im getting Bad Request (#400)

Se recibieron datos erróneos para el parámetro “searchModel”

Any help would be appreciated.


(Softark) #2

You can’t pass $searchModel and $dataProvider as the query parameters to an action method, because they are not such simple variables that could be converted to simple strings.

So you have to create the search model and the data provider in your actionGenerarPdf method.

In order to get back the search parameters used in the index action, you can store the query parameters in the session and retrieve them in actionGenerarPdf.

public function actionIndex()
{
    $session = Yii::$app->session;
    $session->open();
    $session['query_params'] = json_encode(Yii::$app->request->queryParams);
    $session->close();
    ...
}

public function actionGenerarPdf()
{
    $session = Yii::$app->session;
    $session->open();
    $queryParams = isset($session['query_params']) ? json_decode($session['query_params']) : [];
    $session->close();

    $searchModel = new MyModelSearch();
    $dataProvider = $searchModel->search($queryParams);
    ...
}

(Juan Carlos Reyes Suazo) #3

Hi @softark. Im very thankfull for your answer.

Your code is giving me the following error:

PHP Fatal Error – yii\base\ErrorException

Cannot use object of type stdClass as array

    1. in C:\xampp\htdocs\sie2gii\vendor\yiisoft\yii2\base\Model.phpat line 860
* @return bool whether `load()` found the expected form in `$data`. */ public function load($data, $formName = null) { $scope = $formName === null ? $this-&gt;formName() : $formName; if ($scope === '' &amp;&amp; !empty($data)) { $this-&gt;setAttributes($data); return true; } elseif (isset($data[$scope])) { $this-&gt;setAttributes($data[$scope]); return true; } return false; } /**

(Juan Carlos Reyes Suazo) #4

As users Nepaluz, Jon and Svens said in this thread,


I solved this adding ‘true’ into this line:

$queryParams = isset($session['query_params']) ? json_decode($session['query_params'], true) : [];

Adding the true returns the result as an array and not an stdClass


(Softark) #5

Oh, I’ve missed the 2nd parameter true. Sorry :sweat_smile:


(Juan Carlos Reyes Suazo) #6

Nevermind. Thanks for the help :smiley: