Google Chart with Liferay Integration

Google Chart with Liferay Integration

Google Charts are free, powerful, simple to use, open source Business Intelligence software which are used to bring timely, actionable data to the right people at the right time. Liferay is a market leading Portal and Digital Experience Platform that is used to deliver amazing user experiences through multiple digital channels including web and mobile to customers, partners, and employees.This is the reason why Liferay DXP is a great choice.

Now, will it make sense to deliver actionable business intelligence insights to your user base via your enterprise portal? This is where we see increasing demand in the marketplace to integrate Google Charts with Liferay. This article will give you insights of an approach of not only to deliver a truly integrated, fully responsive User Experience but also the dashboards and reports leveraging your Google Charts.

Use Case

Suppose if you wish to create an interactive dashboard creating reports in Google charts and deliver these charts (reports) responsively through Liferay, allowing these reports to interact with each other. In other words, if you select a bar or part of chart or product category in one chart, you want the other reports on the page to refresh based on the event and the selection made of chart.

Mainly google charts are used to represent data with charts, we can identify our data or progress bar or whatever we are looking for it.

Getting Started

1. Create A Liferay Plug-in portet Your Dashboard.

You can use following reference link to create liferay portlet

https://dev.liferay.com/develop/tutorials/-/knowledge_base/6-2/creating-a-liferay-mvc-portlet-project

Note: Configure controller class to get data from DB by Java code or Liferay API’s

Your jsp (page) must have as many HTML elements to hold both the dashboard, the controls and charts. While instantiating dashboard, control, and chart instances, pass a reference to their element, so assign an ID to each HTML element.

   <!–Div that will hold the dashboard–>

    <div id=”dashboard_div“>

      <!–Divs that will hold each control and chart–>

      <div id=”filter_div“></div>

      <div id=”chart_div“></div>

    </div>

The HTML element can be positioned as per your desire, the way you want your dashboard to look.

2. Load Your Libraries

A dashboard requires only two libraries to be included or loaded on the page: the Google AJAX API and the Google Visualization controls package. The API (in particular, google.visualization.ChartWrapper) automatically identifies the other packages needed and loads them on the fly without further intervention.

You must use google.charts.load() to fetch the control library.

<!–Load the AJAX API–>

<script type=”text/javascriptsrc=”https://www.gstatic.com/charts/loader.js”></script>

Note1: We can download/save this js libraries and add it in portlet docroot/js folder and confugure it in liferay-portlet.xml file
Note2: We can add this js libraries in liferay theme as well.

<script type=”text/javascript“>

 

// Load the Visualization API and the controls package.

  // Packages for all the other charts you need will be loaded

  // automatically by the system.

  google.charts.load(‘current’, {‘packages’:[‘controls’]});

 

  // Set a callback to run when the Google Visualization API is loaded.

  google.charts.setOnLoadCallback(drawDashboard);

 

  function drawDashboard() {

    // Everything is loaded. Assemble your dashboard…

  }

</script>

3. Prepare Your Data

When the Visualization API has been loaded, google.charts.setOnLoadCallback() will call your handler function, so you know that all the required helper methods and classes will be ready for you to start preparing your data.

Dashboards accepts data in a DataTable, the same as charts.

var data = google.visualization.arrayToDataTable([

       [‘Employee Name’, ‘Salary’],

       [‘Mike’, {v:22500, f:’22,500′}], // Format as “22,500”.

       [‘Bob’, 35000],

       [‘Alice’, 44000],

       [‘Frank’, 27000],

       [‘Floyd’, 92000],

       [‘Fritz’, 18500]

      ],

      false); // ‘false’ means that the first row contains labels, not data.

Note: We can prepare this data dynamically as well(By fetch from DB).

4. Create a Dashboard Instance

After you have created your data, you can instantiate your dashboard object. A dashboard constructor takes one parameter: a reference to the DOM element in which to draw the dashboard.

 var dashboard = new google.visualization.Dashboard(document.getElementById(‘dashboard_div’));

Dashboards are exposed as a Javascript class. After instantiating your dashboard, you can perform a few optional steps such as adding event listeners (for example, to be notified once the dashboard is ‘ready’). Dashboards handle events in the same way charts do, so refer to Handling Visualization Events or Displaying Errors Nicely in the chart section for more information.

5. Create Control and Chart Instances

Define as many instances you need for each control and chart, that will be part of the dashboard. Use google.visualization.ChartWrapper and google.visualization.ControlWrapper to define charts and controls respectively.

// Create a range slider, passing some options

  var donutRangeSlider = new google.visualization.ControlWrapper({

    ‘controlType‘: ‘NumberRangeFilter‘,

    ‘containerId‘: ‘filter_div‘,

    ‘options‘: {

      ‘filterColumnLabel‘: ‘Donuts eaten’

    }

  });

 

  // Create a pie chart, passing some options

  var pieChart = new google.visualization.ChartWrapper({

    ‘chartType‘: ‘PieChart‘,

    ‘containerId‘: ‘chart_div‘,

    ‘options‘: {

      ‘width‘: 300,

      ‘height‘: 300,

      ‘pieSliceText‘: ‘label’

    }

  });

While creating ChartWrapper and ControlWrapper instances, do not specify either the dataTable or the dataSourceUrl parameter. The dashboard takes care of feeding each of the appropriate data. However, be sure to specify the required parameters: chartType and containerId for charts, controlType and containerId for controls.

A few tips about configuring controls and charts:

You must give all controls a filterColumnIndex (or filterColumnLabel) to specify which column of your google.visualization.DataTable the control operates on (in the example above, the control operates on the column labeled Donuts eaten),
Use the state configuration option on controls to initialize them with an explicit state when they are first drawn. For example, use this setting to fix the initial positions of the thumbs of a range slider control.

var donutRangeSlider = new google.visualization.ControlWrapper({

    ‘controlType‘: ‘NumberRangeFilter‘,

    ‘containerId‘: ‘filter_div‘,

    ‘options‘: {

      ‘filterColumnLabel‘: ‘Donuts eaten’,

      ‘minValue‘: 1,

      ‘maxValue‘: 10

    },

    // Explicitly positions the thumbs at position 3 and 8,

    // out of the possible range of 1 to 10.

    ‘state‘: {‘lowValue‘: 3, ‘highValue‘: 8}

  });

All the charts that are part of a dashboard share the same underlying dataTable you prepared in the Prepare Your Data step. However, charts often require a specific arrangement of columns to display correctly: for example, a pie chart requires a string column for the label, followed by a number column for the value.
Use the view option while configuring each ChartWrapper instance to declare which columns are relevant for the chart, as in the following example.

var data = google.visualization.arrayToDataTable([

    [‘Name’, ‘Gender’, ‘Age’, ‘Donuts eaten’],

    [‘Michael’ , ‘Male’, 12, 5],

    [‘Elisa’, ‘Female’, 20, 7],

    [‘Robert’, ‘Male’, 7, 3],

    [‘John’, ‘Male’, 54, 2],

    [‘Jessica’, ‘Female’, 22, 6],

    [‘Aaron’, ‘Male’, 3, 1],

    [‘Margareth‘, ‘Female’, 42, 8]

  ]);

 

  var pieChart = new google.visualization.ChartWrapper({

    ‘chartType‘: ‘PieChart‘,

    ‘containerId‘: ‘chart_div‘,

    ‘options‘: {

      ‘width‘: 300,

      ‘height‘: 300,

      ‘title‘: ‘Donuts eaten per person’

    },

    // The pie chart will use the columns ‘Name’ and ‘Donuts eaten’

    // out of all the available ones.

    ‘view‘: {‘columns’: [0, 3]}

  });

 

  // The rest of dashboard configuration follows

  // …

6. Draw Your Dashboard

Call the draw() method on the dashboard instance to render the entire dashboard. The draw() method takes only one parameter: the DataTable (or DataView) that powers the dashboard.

You should call draw() every time you change the composition of the dashboard (for example by adding new controls or charts to it) or you change the overall DataTable that powers it.

The dashboard instance fires a ready event whenever draw() terminates drawing all the controls and charts that are part of it. An error event is fired if any of the managed controls or chart fails to draw. To learn more about handling events, see Handling Events.

Note: You should listen for the ready event before you try to change the dashboard composition or draw it again.

7. Programmatic Changes after Draw

Once the dashboard completes the initial draw() it will be live and respond automatically to any action you perform on it (such as changing the selected range of a control slider that is part of the dashboard).
If you need to alter the dashboard state, you can do so by operating directly on the ControlWrapper and ChartWrapper instances that are part of it. The rule of thumb is to perform any change you need directly on the specific ControlWrapper (or ChartWrapper) instance: for example, change a control option or state via setOption() and setState() respectively, and call its draw() method afterward. The dashboard will then update to match the requested changes.