Choose your database:
AnySQL
MySQL
MS SQL Server
PostgreSQL
SQLite
Firebird
Oracle
SQL Anywhere
DB2
MaxDB

Subscribe to our news:
Partners
Testimonials
Philipp Gerber: "

The product is so easy and super built that you can achieve visible and great success after a short time. Also very much possible with the product. A class product. I'm already looking forward to the next versions and extensions. Keep it up.

Support to the product is just perfect. Each Support request is quickly and very competent solved. Also various assistance, which does not fall into a support, are also perfectly processed. There is a direct wire to the manufacturer / developer and this is notth. Thanks for the class Support".

Grey: "We're a two-person company, it's just me an my wife. I'm the technical guru, and she handles the business operations. I have to know a lot about MySQL, but that's much too technical for her. I have frequently had to setup CGI scripts (I code in Perl) so she can manage some of our tables (suppliers, manufacturers, etc).

I discovered PHP Generator a couple of days ago, tried the free version,and within a few hours I had purchased the Pro version (as well as SQL Maestro for MySQL).

Today I am completing the conversion of the last of my custom table managers to PHP Generator. This is eliminating several thousand lines of code that I don't have to support any more!

Thanks for this fantastic product".

More

Add your opinion

SQL Maestro Group / Products / MySQL / PHP Generator for MySQL / Resources / How to add a chart to a webpage created with PHP Generator?

How to add a chart to a webpage created with PHP Generator?

Last modified: May 14, 2013

Prev Next
UPDATE: Starting from the version 16.3 PHP Generator provides direct support for charts based on the Google Chart Library, so you might want to read this article only if you really need to incorporate a different chart library into your application. Otherwise study the examples from our Feature Demo and take a look at the appropriate video lesson.

Abstract

The article illustrates how to add charts to pages produced by PHP Generator with the help of popular chart libraries.

Problem

Charts provide a perfect way to visualize data. You can easily add a chart to a webpage created with PHP Generator using its built-in feature named custom templates and any of available JavaScript chart libraries like freeware Google Chart or commercial tools such as HighChart and FusionCharts.

Solution

The main ideas of webpage appearance customization were described in the previous article. According to them we have to follow these steps:

  • create a new template;
  • instruct PHP Generator to use this template for a certain webpage;
  • add code that renders the chart to the template.

You can find a live example of a page with a chart in our demo application.

In the examples below we will create various charts based on the following result set returned by a query.

The 'Sales By Country' webpage.Picture 1. The 'Sales By Country' webpage.

Example 1

As the first example we take as a goal to add to the top of the 'Sales By Country' page a Geo Chart, a chart with a map of the World with countries filled with colors corresponding to the sales volumes. As a chart library we use Google Charts.

Step 1

First we need to create a custom template file. Of course, you can create the custom template from the scratch, but it's easier to get as a basis the template that is currently used. As we want to modify the appearance of the data grid, we have to use the components/templates/list/grid.tpl template file. Let's copy it to the custom_templates folder with another name, e.g. sales_by_country_edit.tpl.

Step 2

Now we need to specify the generated application to use the new template file for the grid of the sales_by_country webpage. To do this, open the editor of this page in PHP Generator, specify the OnGetCustomTemplate event handler code, and regenerate the application.

Listing 1. OnGetCustomTemplate event handler
if ($part == PagePart::Grid && $mode == PageMode::ViewAll)
  $result = 'sales_by_country_grid.tpl';
The screenshot below displays how the event handler looks in PHP Generator.

Specifying the edit handlerPicture 2. Specifying the edit handler

Step 3

Now the appearance of the grid at the 'Sales By Country' webpage completely depends on the sales_by_country_grid.tpl file content. To add a chart to the page, simply place the necessary code at the beginning of the sales_by_country_grid.tpl file using any text editor.

Listing 2. Chart creation code (Google Geo chart).
{literal}
 
// Loading necessary libraries.
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
 google.load('visualization', '1', {'packages': ['geochart']});
 google.setOnLoadCallback(drawRegionsMap);
 
  // Callback that creates and populates a data table,
  // instantiates the geo chart, passes in the data and draws it.
  function drawRegionsMap() {
 
    // Create the data table and populate it with content of the 'country' and 'total_sales' columns.
    var data = google.visualization.arrayToDataTable([
      ['Country', 'Total Sales']
      {/literal}
      {foreach item=Row from=$DataGrid.Rows name=RowsGrid}
          ,['{$Row.DataCells.country.Data}', {$Row.DataCells.total_sales.Data}]
      {/foreach}
      {literal}
      ]);
 
    // Set chart options.
    var options = {};
 
    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
    chart.draw(data, options);
};
</script>
 
{/literal}
 
// Div that will hold the chart.
<div style="height: 600px; overflow: visible;">
  <div id="chart_div" style="width:900px; height:500"></div>
</div>

The result is shown below.

The result page with the geography chart.Picture 3. The result page with the geography chart.

Example 2

Now we want to add a Column Chart using the Fusion Charts library. To use this package, we need to copy all the library files to any directory of the computer the webserver is installed on.

The first and second steps in this case are the same as in the previous example. The block code corresponding to the selected chart is shown below.

Listing 3. Creating a column chart with the Fusion Charts library.
{literal}
 
<script language="Javascript" src="FusionCharts/Charts/FusionCharts.js"></script>
 
{/literal}
 
{php}
 
// Loading necessary libraries.
include "FusionCharts/Code/PHPClass/Includes/FusionCharts_Gen.php";
 
// Creating the appropriate object.
$FC = new FusionCharts("Column2D", "800", "400");
 
// Populating the data.
$DataGrid=$this->get_template_vars('DataGrid');
foreach ($DataGrid['Rows'] as $row)
    $FC->addChartData($row['DataCells']['total_sales']['Data'], "Label=".$row['DataCells']['country']['Data']);
 
// Adding the chart to the webpage.
$FC->setRenderer('javascript');
$FC->renderChart();
{/php}

Here you can see the result of our operations.

The 'Sales By Country' webpage with the Fusion column chartPicture 4. The 'Sales By Country' webpage with the Fusion column chart.

Example 3

Now let's add a Pie Chart of the HighCharts library. As in the previous example we skip to the third step. The code that should be entered into the sales_by_country_grid.tpl file is as follows.

Listing 4. Creating a pie chart with the HighCharts library.
{literal}
 
// Loading necessary libraries.
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
 
//Setting chart options.
<script type="text/javascript">
$(function () {
    $('#container').highcharts({
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
 
	    title: {
                text: ''
            },
 
	    tooltip: {
                pointFormat: '{series.name}:<b>{point.percentage:.1f}%</b>',percentageDecimals: 1
            },
 
	    plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                    }
                }
            },
 
	    title: '',
 
            series: [{
                type: 'pie',
                data: [
		{/literal}
 
                // Preparing the data for the chart.
		{foreach item=Row from=$DataGrid.Rows name=RowsGrid}
		    {if $smarty.foreach.RowsGrid.index > 0}
		    ,
		    {/if}
	            ['{$Row.DataCells.country.Data}',
		    {$Row.DataCells.total_sales.Data}]
		{/foreach}
 
                {literal}
		]
	    }]
        });
    });
</script>
{/literal}
 
// Adding the chart to the webpage.
<div id="container" style="width: 100%; height: 400px;"></div>

The result is shown below.

The 'Sales By Country' webpage with a pie chart.Picture 5. The 'Sales By Country' webpage with a pie chart.

Conclusion

We hope you have been convinced of the simplicity of working with chart libraries in PHP Generator and now the only limit of using charts on your webpages is your imagination!

Prev Next