Calum Harrison logo
  • Home 
  • Tags 
  • About Me 
  1. Home
  2. Posts
  3. Part 2: Why consider Chart.js with Power Pages

Part 2: Why consider Chart.js with Power Pages

Posted on November 13, 2024  (Last modified on November 30, 2024) • 3 min read • 604 words
Power Pages   Chartjs   Reporting  
Power Pages   Chartjs   Reporting  
Share via
Calum Harrison
Link copied to clipboard

On this page
  • Prerequisites
  • Build time
  • Breakdown of code
  • Conclusion
Part 2: Why consider Chart.js with Power Pages
Photo by Nick Brunner on unsplash

In Part 1 of the series we looked at how to setup a simple chart using the Chart.js library, in this blog we are going to go one step further and build a chart to display data from Dataverse.

Prerequisites  

  • Experience with using the web API with Power Pages, as the setup and concepts will not be discussed.

Build time  

In this example we are showing the amount of sales grouped by order status.

Image of a bar chart using data from Dataverse.
Image of a bar chart using data from Dataverse.

  Note

Code has been stored in a web template due to its complex requirements. To avoid confusion as I use a slight variation for AJAX calls, I have left a placeholder for you to add your own AJAX call. The Dataverse Rest Builder is a great tool for this.

Copy the below JS code to a web template.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"> </script>

<div class="wrapper-body">
    <div id="mainContent">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    {% block main %}
                    {% include 'Page Copy' %}
                    <div class="simpleChart">
                        <h2> Example of a simple chart</h2>
                    </div>

                    <div class="customChart">
                        <h2> Example of a complex chart</h2>
                        <canvas id="myChartCustom" style="width:100%;max-width:600px"></canvas>

                    </div>
                    {% endblock %}
                </div>
            </div>
        </div>
    </div>
</div>

<script>

    document.addEventListener("DOMContentLoaded", () => {

       // ***IMPORTANT - include your GET AJAX call to assign the response of data to the results variable
       // ***IMPORTANT once the AJAX call has been added, make sure to add the closing bracket etc to the end of the script section

            const results = data.value;

            let aggregatedData = {};

            // Iterate through the data and aggregate amounts by status
            for (let i = 0; i < results.length; i++) {
                const result = results[i];
                const ch_status = result["ch_status"]; // Choice
                const ch_status_formatted = result["ch_status@OData.Community.Display.V1.FormattedValue"];
                let ch_totalamount = result["ch_totalamount"]; // Currency

                // Use formatted status or fallback to raw status code
                const statusDisplay = ch_status_formatted || `Status Code ${ch_status}`;

                // Group and sum the total amounts by status
                if (aggregatedData[statusDisplay]) {
                    aggregatedData[statusDisplay] += ch_totalamount;
                } else {
                    aggregatedData[statusDisplay] = ch_totalamount;
                }
            }

            // Prepare xValues and yValues arrays for the chart
            const xValues = Object.keys(aggregatedData);
            const yValues = Object.values(aggregatedData);

            const barColors = ["red", "green", "blue"]; // Adjust or add logic to dynamically assign colors as needed

            // Initialise the chart with the aggregated data
            new Chart("myChartCustom", {
                type: "bar",
                data: {
                    labels: xValues,
                    datasets: [{
                        backgroundColor: barColors.slice(0, xValues.length),
                        data: yValues
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: { display: false },
                        title: {
                            display: true,
                            text: "Sales amounts by status"
                        }
                    }
                }
            });
        });
</script>

Breakdown of code  

  • Use the Web API to retrieve all sales orders including the total amount and status field.
  • For each sales order returned from the API call, the code aggregates the total amounts and groups it by status.
  • The X and Y values are assigned to the aggregatedData object using the data and keys.
  • Finally, a Chart.js bar chart is initialized and rendered on the page to visually display the sales amounts grouped by status.

Conclusion  

😁Thanks for reading, as we have seen throughout the 2 part series, the Chart.js library can be used to display rich visualisations with using local or external data. There is a potential to extend this by using filters in the AJAX call to only show records that belong to the end user but its really important to note that with exposing any external data make sure all appropriate security controls (table permissions etc) that Power Pages provides are used. If there is any sensitive data make sure to check out Power BI in the first instance.

Have a great day!

 Be transparent with end users by using a maintenance page
Part 1: Why consider Chart.js with Power Pages 
On this page:
  • Prerequisites
  • Build time
  • Breakdown of code
  • Conclusion
Follow me on LinkedIn

 
Copyright © 2025 Calum Harrison. | Powered by Hinode.
Calum Harrison
Code copied to clipboard