The example demonstrates usage of CalculatedColumn
process. The CalculatedColumn process creates new column and use formula to create value. As you may see there are two ways to enter formula. You can define formula in string and wrapped field name in bracket "{hour_rate}*{working_hours}"
. Second option, you can define your own custom function to calculate value as you see the "total_by_func"
in above example.
<?php
require_once "MyReport.php";
$report = new MyReport;
$report->run()->render();
<?php
//Step 1: Load KoolReport
require_once "../../../load.koolreport.php";
use \koolreport\processes\ColumnMeta;
use \koolreport\processes\CalculatedColumn;
//Step 2: Creating Report class
class MyReport extends \koolreport\KoolReport
{
protected function settings()
{
return array(
"dataSources"=>array(
"data"=>array(
"class"=>'\koolreport\datasources\ArrayDataSource',
"dataFormat"=>"table",
"data"=>array(
array("name","hour_rate","working_hours"),
array("John",20,123),
array("Marry",30,112),
array("Peter",25,132),
array("Donald",40,89),
)
)
)
);
}
protected function setup()
{
//Prepare data
$this->src("data")
->pipe(new ColumnMeta(array(
"hour_rate"=>array(
"type"=>"number",
"prefix"=>'$',
"suffix"=>'/hrs',
),
"working_hours"=>array(
"type"=>"number",
"suffix"=>' hrs',
),
)))
->saveTo($source);
//Save orginal data
$source->pipe($this->dataStore("origin"));
//Pipe through process to get result
$source->pipe(new CalculatedColumn(array(
"total"=>"{hour_rate}*{working_hours}",
"total_by_func"=>function($row){
return $row["hour_rate"]*$row["working_hours"];
}
)))
->pipe(new ColumnMeta(array(
"total"=>array(
"type"=>"number",
"prefix"=>'$'
),
"total_by_func"=>array(
"type"=>"number",
"prefix"=>'$'
)
)))
->pipe($this->dataStore("result"));
}
}
<?php
use \koolreport\widgets\koolphp\Table;
use \koolreport\widgets\google\LineChart;
?>
<div class="report-content">
<div class="text-center">
<h1>CalculatedColumn Process</h1>
<p class="lead">Calculated column by expression or function</p>
</div>
<?php
Table::create(array(
"dataSource"=>$this->dataStore("origin"),
"cssClass"=>array(
"table"=>"table-bordered table-striped table-hover"
)
));
?>
<i class="fa fa-arrow-down" style="font-size:24px;"></i>
<pre style="font-weight:bold"><code>
->pipe(new CalculatedColumn(array(
"total"=>"{hour_rate}*{working_hours}",
"total_by_func"=>function($row){
return $row["hour_rate"]*$row["working_hours"];
}
)))
</code></pre>
<i class="fa fa-arrow-down" style="font-size:24px;"></i>
<div style="margin-top:20px;">
<?php
Table::create(array(
"dataSource"=>$this->dataStore("result"),
"cssClass"=>array(
"table"=>"table-bordered table-striped table-hover"
)
));
?>
</div>
</div>