Create pdf with information and attributes of various models

Good day
I need to make 1 PDF file with information from several tables in the database and bringing the attributes of different models, I am using the extension of Kartik MPDF to generate the pdf, I could already generate it from the first model but I need that in that pdf it is all the related information by means of a Foreign Key, thanks in advance, I append the code that I have in the driver of the model that the PDF already generates

public function actionPdf($id)
{     
 Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$pdf = new Pdf([
    'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
    'destination' => Pdf::DEST_BROWSER,
    'content' => $this->renderPartial('pdf1', ['model'=>$this->findModel($id)]),
    'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
    'filename'=>'Ficha',
    'options' => [
        // any mpdf options you wish to set
    ],
    'methods' => [
        'SetTitle' => 'Title',
        'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
        'SetHeader' => ['Title||Generated On: ' . date("r")],
        'SetFooter' => ['|Page {PAGENO}|'],
        'SetAuthor' => 'Kartik Visweswaran',
        'SetCreator' => 'Kartik Visweswaran',
        'SetKeywords' => 'Krajee, Yii2, Export, PDF, MPDF, Output, Privacy, Policy, yii2-mpdf',
    ]
]);
return $pdf->render();

}

What have you tried so far?

I am working with the Kartik extension for mpdf, I have created the action in the controller that will generate the pdf, do not create a separate driver for the PDF, just one action, create the pdf file in the folder view of the model "Company “which is the model since I am generating the PDF, I could already generate pdf of that specific model but I have not been able to bring the models that are related by means of a foreign key” id_empresa "in the other models, but it only generates me pdf with the information when the pdf file I put the Detail view of that model.

Action in the EmpresaController driver

public function actionPdf($id)
    {
        $model = $this->findModel($id);
        $datos = [$id];
        $content = $this->renderPartial('pdf1',[
            'model'=>$model,
            'data'=>$datos,            
            ]);    
        Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
        $pdf = new Pdf([
        'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
        'destination' => Pdf::DEST_BROWSER,
        'content'=>$content,   
        'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
        'filename'=>'Ficha',
        'options' => [
            // any mpdf options you wish to set
        ],
        'methods' => [
            'SetTitle' => 'Ficha Acueducto - PDA',
            'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
            'SetHeader' => ['Ficha Acueducto - PDA||Generated On: ' . date("r")],
            'SetFooter' => ['|Page {PAGENO}|'],
            'SetAuthor' => 'Kartik Visweswaran',
            'SetCreator' => 'Kartik Visweswaran',
            'SetKeywords' => 'Krajee, Yii2, Export, PDF, MPDF, Output, Privacy, Policy, yii2-mpdf',
        ]
    ]);
    return $pdf->render();
}

File code pdf1 in the Empresa view

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;


/* @var $this yii\web\View */
/* @var $model app\models\Empresa */

$this->title = $model->nombre_empresa;
?>
<h1><title><?= Html::encode($this->title) ?></title></h1>
<div class="empresa-view">
    <?= DetailView::widget([
                'model' => $model,
        'attributes' => [
            'id',
            'nombre_empresa',
            'foto',
            'telefono',
            'email:email',
            'natu_juridica',
            'limite_norte',
            'limite_sur',
            'limite_oriente',
            'limite_occidente',
            'n_suscriptores',
            'logo',
            'mision:ntext',
            'vision:ntext',
            'manual_funciones',
            'uso_agua',
            'tarifa_promedio',
            'periodo_cobro',
            'created_at',
            'created_by',
            'updated_at',
            'updated_by',
        ],
    ]) ?>
</div>

It’s possible to render the related models of Empresa in your 'pdf1' view.
What related models does Empresa have?

These are the models related to the “Empresa” model

public function getActividads()
{
return $this->hasMany(Actividad::className(), [‘id_empresa’ => ‘id’]);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getCoberturaas()
{
    return $this->hasMany(Coberturaa::className(), ['id_empresa' => 'id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getCoberturaals()
{
    return $this->hasMany(Coberturaal::className(), ['id_empresa' => 'id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getFinancieros()
{
    return $this->hasMany(Financiero::className(), ['id_empresa' => 'id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getIntegrantes()
{
    return $this->hasMany(Integrante::className(), ['id_empresa' => 'id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getPersonals()
{
    return $this->hasMany(Personal::className(), ['id_empresa' => 'id']);
}

}

So, an Empresa has many Activedads. Am I right?
Then you can access the Activedads related to the current Empresa like the following in your pdf1 view:

    foreach($model->activedads as $activedad) {
        echo $activedad->name; // or some attribute of Activedad
    }

The same goes for Coberturaa, Coberturaal, Financiero, Integrante and Personal.

$model = Empresa::findOne($id);
foreach($model->coberturaas as $coberturaa) {
    echo $coberturaa->name;
}
foreach($model->coberturaals as $coberturaal) {
    echo $coberturaal->name;
}
foreach($model->financieros as $financiero) {
    echo $financiero->name;
}
foreach($model->integrates as $integrate) {
    echo $integrate->name;
}

name may not be a valid attribute. You can replace it with any valid attribute.

But the key concept is that you can access the related models of Empresa without worrying about emresa_id and the SQLs to get the related models once you have established the relations.

a question those foreach should I put them in the driver or in the pdf1 file where the pdf is generated

You may put those foreach loops in the controller or in the view script. The both will do. But I would do it in the view script because it will be simpler.

good day

Thanks for the help I was able to do the pdf that I needed, I append the code that I use so that another person can be of help

Thank you

Controller

public function actionPdf($id)
    {
        $model = Empresa::findOne(1);
        $datos=[1,2,4,5];
        $content = $this->renderPartial('pdf1',[
            'model'=>$model,        
            'data'=>$datos,
            ]);    
        Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
        $pdf = new Pdf([
        'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
        'destination' => Pdf::DEST_BROWSER,
        'content'=>$content,   
        'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
        'filename'=>'Ficha',
        'options' => [
            // any mpdf options you wish to set
        ],
        'methods' => [
            'SetTitle' => 'Ficha Acueducto - PDA',
            'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
            'SetHeader' => ['Ficha Acueducto - PDA||Generado el: ' . date("r")],
            'SetFooter' => ['|Pagina {PAGENO}|'],
            'SetAuthor' => 'PDA - Caldas',
            'SetCreator' => 'PDA -Caldas',
            'SetKeywords' => 'Krajee, Yii2, Export, PDF, MPDF, Output, Privacy, Policy, yii2-mpdf',
        ]
    ]);
    return $pdf->render();
}

View PDF

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;


/* @var $this yii\web\View */
/* @var $model app\models\Empresa */

$this->title = $model->nombre_empresa;
?>
<h1><?= Html::encode($this->title) ?></h1>
    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'nombre_empresa',
            'foto',
            'telefono',
            'email:email',
            'natu_juridica',
            'limite_norte',
            'limite_sur',
            'limite_oriente',
            'limite_occidente',
            'n_suscriptores',
            'logo',
            'mision:ntext',
            'vision:ntext',
            'manual_funciones',
            'uso_agua',
            'tarifa_promedio',
            'periodo_cobro',
        ],
    ]) ?>
<h1><?= Html::encode('Tipo de Personal Contratado') ?></h1>
        <?php
foreach($model->personals as $personal){
    ?> 
        <?=DetailView::widget([
        'model' => $personal,
        'attributes' => [
            'area',
            'cantidad',
            'tipo_vinculacion',
            'observaciones:ntext',
        ],
    ]); 
}
?>
<h1><?= Html::encode('Personal Contratado') ?></h1>
<?php
foreach($model->integrantes as $integrante){
    ?> 
        <?=DetailView::widget([
        'model' => $integrante,
        'attributes' => [
            'nombre_integrante',
            'personal.area',
            'genero',
            'telefono',
        ],
    ]); 
}
?>
<h1><?= Html::encode('Información Financiera') ?></h1>
    <?php
foreach($model->financieros as $financiera){
    ?> 
        <?=DetailView::widget([
        'model' => $financiera,
        'attributes' => [
            'valor_facturado',
            'valor_recaudado',
            'cartera_morosa',
            'micromedicion',
            'concesion_agua',
            'fecha_concesion',
            'agente_contaminante:ntext',
            'proteccion_franja',
        ],
    ]); 
}
?>
<h1><?= Html::encode('Infraestructura Existente') ?></h1>
<?php
foreach($model->infraestructuras as $infraestructura){
    ?> 
        <?=DetailView::widget([
        'model' => $infraestructura,
        'attributes' => [
            'elemento',
            'cantidad',
            'material',
            'estado',
        ],
    ]); 
}
?>
<h1><?= Html::encode('Cobertura Acueducto') ?></h1>
<?php
foreach($model->coberturaas as $acueducto){
    ?> 
        <?=DetailView::widget([
        'model' => $acueducto,
        'attributes' => [
            'irca',
            'f_abastecedora',
            'con_servicio',
            'cal_servicio',
            'ver_benefi',
        ],
    ]); 
}
?>
<h1><?= Html::encode('Cobertura Alcantarillado') ?></h1>
<?php
foreach($model->coberturaals as $alcantarillado){
    ?> 
        <?=DetailView::widget([
        'model' => $alcantarillado,
        'attributes' => [
            'empresa_prestadora',
            'n_suscriptores',
            'f_receptora',
            'tratamiento_a_resi',
            'cobertura_r',
        ],
    ]); 
}
?>
<h1><?= Html::encode('Cobertura Aseo') ?></h1>
<?php
foreach($model->coberturaaseos as $aseo){
    ?> 
        <?=DetailView::widget([
        'model' => $aseo,
        'attributes' => [
            'empresa_prestadora',
            'n_suscriptores',
            'tipo_tratamiento',
            'sitio_dispo_final',
            'lugar_relleno',
            't_residuos_s_2016',
            't_residuos_s_2017',
            'cant_rutas',
            'f_barridos',
            'n_veces_recoleccion',
        ],
    ]); 
}
?>
2 Likes

Thank you for your feedback.:grinning:

where is the link button that generate PDF