KoolReport's Forum

Official Support Area, Q&As, Discussions, Suggestions and Bug reports.
Forum's Guidelines

CakePHP 4.0 PDF Export using Cloud Export #2639

Open Imad opened this topic on on Apr 15, 2022 - 14 comments

Imad commented on Apr 15, 2022

I'm trying to do an export as per examples in the forums. The report works and the cakephp view file is : report.php

In the Controller I have a class:

class emReportsController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
    }

    public function export()
    {
        require_once "report.php";
        $report = new report;    __<---- it says this is Undefined__
        $report->run();

        $secretToken = 'xxxxxxxxx My token is here xxxxxxxxxxxx';
        $type = isset($_GET['type']) ? $_GET['type'] : 'PDF';
        $settings = [
            "pageWaiting" => "networkidle2", //load, domcontentloaded, networkidle0, networkidle2
        ];

        $pdfOptions = [
            "format" => "A4",
            'landscape' => false,
            "noRepeatTableFooter" => true,
        ];
        $report->cloudExport("report")
            ->chromeHeadlessio($secretToken)
            ->settings($settings)
            ->pdf($pdfOptions)
            ->toBrowser("MyReport.pdf");
    }
 public function report()
    {
        $year = date("Y");
        $year_range = range('1990', $year);
        $year_range = array_reverse(array_combine($year_range, $year_range), true);

        $report_year = $year - 1;
        if ($this->request->is('post')) {
            $posted_data = $this->request->getData();
            if ($posted_data['year_input']) {
                $report_year = $posted_data['year_input'];
            }
        }

        $this->loadComponent('Utilities');
        //Look up Lists
        $plant_list = $this->Utilities->look_up('EmLuPlants');
        $species_list = $this->Utilities->look_up('EmLuProcessedSpecies');
        $gender_list = $this->Utilities->look_up('EmLuGenders');
        $education_list = $this->Utilities->look_up('EmLuEducationLevels');
        $status_list = $this->Utilities->look_up('EmLuWorkStatus');
        $km_traveled_list = $this->Utilities->look_up('EmLuKmTraveled');

        //21 Total number of factory workers overall, by plant
        $query = $this->fetchTable('EmPlants')->find();
        $result = $query->select([
            'total' =>  $query->func()->COUNT('DISTINCT em_profiles_id'),
            'year' => 'year_worked',
            'plant' => 'em_plants_id'
        ])->group('	year_worked,em_plants_id')->where(['year_worked =' => $report_year]);

        $total_by_factory["dataSource"] = [];
        foreach ($result as $key => $val) {
            $total_by_factory["dataSource"][] = ["year" => $val['year_worked'], "plant" => $plant_list[$val['plant']], "total" => $val['total']];
        }

        //22 Total number of foreign workers overall, by plant
        $query = $this->fetchTable('EmPlants')->find();
        $result = $query->select([
            'total' =>  $query->func()->COUNT('DISTINCT EmPlants.em_profiles_id'),
            'statusid' => 'citizen_status_id',
            'plant' => 'EmPlants.em_plants_id'
        ])->join([
            "table" => "em_profiles",
            "type" => "INNER",
            "conditions" => "EmPlants.em_profiles_id= em_profiles.em_profiles_id"
        ])->where(['citizen_status_id =' => 4])->group('em_plants_id')->having(['total >=' => 1])->toArray();

        $foreign_workers["dataSource"] = [];
        foreach ($result as $key => $val) {
            $foreign_workers["dataSource"][] = ["statusid" => $val['statusid'], "plant" => $plant_list[$val['plant']], "total" => $val['total']];
        }

        //23.1 Overall average age, by plant
        $query = $this->fetchTable('EmVwAgeInPlant')->find();
        $result = $query->select([
            'age' =>  $query->func()->AVG('age'),
            'plant' => 'plant_id'
        ])->group('plant_id')->toArray();

        $avg_age_plant["dataSource"] = [];
        foreach ($result as $key => $val) {
            $avg_age_plant["dataSource"][] = ["plant" => $plant_list[$val['plant']], "age" => $val['age']];
        }

        //23.2 Overall average age by plant, by male
        $query = $this->fetchTable('EmVwAgeInPlant')->find();
        $result = $query->select([
            'age' =>  $query->func()->AVG('age'),
            'plant' => 'plant_id'
        ])->group('plant_id')->where(['gender_id =' => 1])->toArray();

        $avg_age_plant_male["dataSource"] = [];
        foreach ($result as $key => $val) {
            $avg_age_plant_male["dataSource"][] = ["plant" => $plant_list[$val['plant']], "age" => $val['age']];
        }

}

This is the report.php view --- This view works very well

<?php
$this->layout = "registryMain";

use koolreport\widgets\google\BarChart;

?>
<div class='shadow p-3 my-3'>
    <h1 class="text-center"><?= __("Random Ratio Reports - All History") ?></h1>

    <div class="d-flex justify-content-end">
        <div class="col-1 border">
            <?php
            echo $this->Form->create(NULL, [
                "class" => "form-horizontal needs-validation",
                "id" => "report_year",
                "novalidate" => true,
            ]);

            echo $this->Form->select('year_input', $year_range, [
                "id" => "year_input",
                "class" => 'form-control multiselect-select2 nosearch',
            ]);
            ?>
        </div>
        <button type="submit" name="submit" class="btn btn-secondary">Submit</button>
    </div>

<?php
echo $this->Form->end();

//21 Total number of factory workers overall, by plant
if (!empty($total_by_factory["dataSource"])) {
    BarChart::create(array(
        "title" => __("21 Total number of factory workers overall, by plant - year 2000"),
        "dataSource" => $total_by_factory["dataSource"],
        "columns" => array(
            "plant",
            "total" => array(
                "label" => __("total"),
                "type" => "number",
            ),

        ), "options" => array(
            "isStacked" => true
        )
    ));
} else {
    echo "<br>", __("No Data Available for Total number of factory workers overall, by plant");
}

//22 Total number of foreign workers overall, by plant
if (!empty($foreign_workers["dataSource"])) {
    BarChart::create(array(
        "title" => __("22 Total number of foreign workers overall, by plant"),
        "dataSource" => $foreign_workers["dataSource"],
        "columns" => array(

            "plant",
            "total" => array(
                "label" => __("total"),
                "type" => "number",
            ),

        ), "options" => array(
            "isStacked" => true
        )
    ));
} else {
    echo "<br>", __("No Data Available for Total number of foreign workers overall, by plant");
}



Sebastian Morales commented on Apr 18, 2022

Pls post the code of your "report.php" class file. It must have a class named "report". Pls check our quick start guide for a report structure:

https://www.koolreport.com/docs/quick_start/

KoolReport commented on Apr 18, 2022

If inside report.php, you have a report class called MyReport then you use that class name to create report object:

require_once "report.php";
$report = new MyReport;
...
Imad commented on Apr 18, 2022

This is what I have in report.php... it fixed the undefined, but how do I get it to work? I still get "empty export content"

<?php
class MyReport extends \koolreport\KoolReport
{
    //Register cloud export service in your report
    use \koolreport\cloudexport\Exportable;
}

I'm using the CakePHP4 framework. The way files are organized are not the same as the way the tutorials on the quick_start page.

KoolReport commented on Apr 19, 2022

Here is an sample koolreport inside cakephp. Hope that helps.

Imad commented on Apr 19, 2022

The sample report inside cakephp is what I implement to get the reports to display. This works, I don't have a problem. I am trying figure out how to export PDF using the cloudExport using CakePHP 4. The export documentation doesn't work in CakePHP. Any other ideas?

Sebastian Morales commented on Apr 20, 2022

Pls post your report setup, pdf view, and export command code. Tks,

Imad commented on Apr 20, 2022

The code is in the original post. Is that what you're looking for?

Sebastian Morales commented on Apr 21, 2022

Pls post the content of your report.php and report.view.php files.

Imad commented on Apr 21, 2022

Hi Sebastien, my code is what I posted in the original post. The first part is the controller which has "export" and "report" functions. the second part is the view.

It's the way CakePHP renders the view. The view actually works. It's the export that I'm having an issue with.

Sebastian Morales commented on Apr 22, 2022

I don't see the content of report.php and report.view.php, only your report() function which is not the same. It's advisable to use a separate view for pdf export. For example, you could use a simple pdf view like this:

<!-- MyReportPDF.vew.php -->
Hello world

And export command:

$report->cloudExport("MyReportPDF") // use MyReportPDF view in MyReportPDF.view.php file
            ->chromeHeadlessio($secretToken)
            ->settings($settings)
            ->pdf($pdfOptions)
            ->toBrowser("MyReport.pdf");
Imad commented on Apr 22, 2022

this is my report view (it's at the bottom of my original post):

How will cakePhp know to use the report. It's usually through routing.

<?php
$this->layout = "registryMain";

use koolreport\widgets\google\BarChart;

?>
<div class='shadow p-3 my-3'>
    <h1 class="text-center"><?= __("Random Ratio Reports - All History") ?></h1>

    <div class="d-flex justify-content-end">
        <div class="col-1 border">
            <?php
            echo $this->Form->create(NULL, [
                "class" => "form-horizontal needs-validation",
                "id" => "report_year",
                "novalidate" => true,
            ]);

            echo $this->Form->select('year_input', $year_range, [
                "id" => "year_input",
                "class" => 'form-control multiselect-select2 nosearch',
            ]);
            ?>
        </div>
        <button type="submit" name="submit" class="btn btn-secondary">Submit</button>
    </div>

<?php
echo $this->Form->end();

//21 Total number of factory workers overall, by plant
if (!empty($total_by_factory["dataSource"])) {
    BarChart::create(array(
        "title" => __("21 Total number of factory workers overall, by plant - year 2000"),
        "dataSource" => $total_by_factory["dataSource"],
        "columns" => array(
            "plant",
            "total" => array(
                "label" => __("total"),
                "type" => "number",
            ),

        ), "options" => array(
            "isStacked" => true
        )
    ));
} else {
    echo "<br>", __("No Data Available for Total number of factory workers overall, by plant");
}

//22 Total number of foreign workers overall, by plant
if (!empty($foreign_workers["dataSource"])) {
    BarChart::create(array(
        "title" => __("22 Total number of foreign workers overall, by plant"),
        "dataSource" => $foreign_workers["dataSource"],
        "columns" => array(

            "plant",
            "total" => array(
                "label" => __("total"),
                "type" => "number",
            ),

        ), "options" => array(
            "isStacked" => true
        )
    ));
} else {
    echo "<br>", __("No Data Available for Total number of foreign workers overall, by plant");
}
Sebastian Morales commented on Apr 25, 2022

Pls try the view like I suggested in the previous post and see if cloud export returns a pdf file with "Hello world" string:

https://www.koolreport.com/forum/topics/2639#p14574

Imad commented on Apr 28, 2022

The post you suggested definitely works, I'm trying to integrate it with CakePHP (specifically version 4). I am not sure how to set it up within the framework.

Sebastian Morales commented on May 2, 2022

Did you mean the pdf view file with "Hello world" string is exported to pdf successfully?

Build Your Excellent Data Report

Let KoolReport help you to make great reports. It's free & open-source released under MIT license.

Download KoolReport View demo
help needed

Export