Wednesday, March 16, 2016

Google Chart examples in Office 365 Sites and SharePoint

Some days ago i was playing around with the Google api and found the Google Charts and was surprise how different are from the older version....
But yes, everyone is talking about SP2016, Power BI for Data and visualization, but decide to give a try and make some examples integrating the Chart API with SharePoint List "Classic"... 
For this example i use the html from the chart to inject in the SharePoint Modal Dialog and not any support page to generate the reports, i try to keep very simple in the architectural approach.

There is another interesting Chart call "Org Chart" that make my attention and of course i will try to integrate in the user profile "another classic" but that is another article.
Right now i like to play with this API and make some example in JavaScript and of course my favorite topic create Custom Ribbons Actions. :)

Here the link from the Google Charts API.
https://developers.google.com/chart/ 

All the Ribbons were made using the following tool "Processlynx Ribbon Manager"
http://aaclage.blogspot.ch/2014/06/sharepoint-app-processlynx-custom.html

For other Examples of Ribbons Customization in SharePoint/Office 365 i would like the recommend the following link:
http://aaclage.blogspot.ch/2016/03/part-v-examples-of-ribbons.html

Configuration of the Chart Examples

To support the example was created a custom List with the Columns "Country, Sales". 
where should display the amount of sales by country.
For the Ribbons was create an FlyoutAnchor where are listed the different Ribbons Options "Bar Chart, Pie Chart and All Charts", when selected should popup the SharePoint Modal Dialog with the chart's associated.
If you make changes on the list using Quick Edit the Chart will reflect the changes without need of refresh the page.


For the XML structure of the Ribbon Configuration you can use the following:
<CommandUIExtension xmlns=\"http://schemas.microsoft.com/sharepoint/\">\n<CommandUIDefinitions>\n<CommandUIDefinition Location=\"Ribbon.List.Settings.Controls._children\">\n<FlyoutAnchor Id=\"Chart Example\" LabelText=\"Chart Examples\" Image32by32=\"/_layouts/15/1033/images/formatmap32x32.png?rev=33\" Image32by32Left=\"-0\" Image32by32Top=\"-407\" Command=\"Chart Example.Command\" TemplateAlias=\"o1\">\n<Menu Id=\"Chart Example.Menu\">\n<MenuSection Id=\"Charts\" DisplayMode=\"Menu32\">\n<Controls Id=\"Charts.Controls\">\n<Button Id=\"barChart\" LabelText=\"Bar Chart\" Image32by32=\"/_layouts/15/1033/images/formatmap32x32.png?rev=33\" Image32by32Left=\"-271\" Image32by32Top=\"-35\" ToolTipTitle=\"Bar Chart\" Command=\"barChart.Command\" TemplateAlias=\"o1\" />\n<Button Id=\"PieChart\" LabelText=\"Pie Chart\" Image32by32=\"/_layouts/15/1033/images/formatmap32x32.png?rev=33\" Image32by32Left=\"-272\" Image32by32Top=\"-170\" ToolTipTitle=\"Pie Chart\" Command=\"PieChart.Command\" TemplateAlias=\"o1\" />\n<Button Id=\"AllCharts\" LabelText=\"All charts\" Image32by32=\"/_layouts/15/1033/images/formatmap32x32.png\" Image32by32Left=\"-474\" Image32by32Top=\"-69\" ToolTipTitle=\"All charts\" Command=\"AllCharts.Command\" TemplateAlias=\"o1\" />\n</Controls>\n</MenuSection>\n</Menu>\n</FlyoutAnchor>\n</CommandUIDefinition>\n</CommandUIDefinitions>\n<CommandUIHandlers>\n<CommandUIHandler Command=\"Chart Example.Command\" CommandAction=\"\" />\n<CommandUIHandler Command=\"barChart.Command\" CommandAction=\"<CodeBar>\" />\n<CommandUIHandler Command=\"PieChart.Command\" CommandAction=\"<CodePie>\" />\n<CommandUIHandler Command=\"AllCharts.Command\" CommandAction=\"<CodeAllCharts>\" />\n</CommandUIHandlers>\n</CommandUIExtension>


Bar Chart Example

The Ribbon Custom Action "Bar Chart" read the List items from the Custom List and display in a html SharePoint Modal Dialog as Bar Chart.


Code Bar charts:

javascript:
    function DialogApps(element) {
        SP.UI.ModalDialog.showModalDialog({
            html: element,
            title: "Google Chart Example",
            allowMaximize: false,
            showClose: true,
            autoSize: true,
            height: 600,
            width: 600,
        });
    }

function drawStuff(array) {
    var data = new google.visualization.arrayToDataTable(array);

    var options = {
        title: 'Chart Example',
        width: 600,
        height: 600,
        legend: {
            position: 'none'
        },
        chart: {
            subtitle: 'Sales by Country'
        },
        bars: 'horizontal',
        axes: {
            x: {
                0: {
                    side: 'top',
                    label: 'Sales'
                } // Top x-axis.
            }
        },
        bar: {
            groupWidth: "90%"
        }
    };
    var element = document.createElement('div');
    element.setAttribute("id", "top_x_div");
    var chart = new google.charts.Bar(element);
    chart.draw(data, google.charts.Bar.convertOptions(options));
    DialogApps(element);
}

function ChartLoad() {
    google.charts.load('current', {
        'packages': ['bar', 'corechart']
    });
    google.charts.setOnLoadCallback(GetListItems);
}

function GetListItems() {
    var ctx = new SP.ClientContext.get_current();
    var targetList = ctx.get_web().get_lists().getById(SP.ListOperation.Selection.getSelectedList());
    var query = SP.CamlQuery.createAllItemsQuery();

    var queryResults = targetList.getItems(query);
    ctx.load(queryResults);

    ctx.executeQueryAsync(function getDocsAllItemsSuccess(sender, args) {
            var array = [];
            array.push(['Country', 'Sale']);
            var listEnumerator = queryResults.getEnumerator();
            while (listEnumerator.moveNext()) {
                array.push([listEnumerator.get_current().get_item("Title"), listEnumerator.get_current().get_item("Sales")]);
            }
            drawStuff(array);
        },
        function getDocsAllItemsFailure(sender, args) {
            alert('Failed to get list items. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
        });
}

SP.SOD.registerSod("Chart", "//www.gstatic.com/charts/loader.js");
SP.SOD.executeFunc('Chart', false, ChartLoad);
GetListItems();

Pie Chart Example

The Ribbon Custom Action "Pie Chart" read the List items from the Custom List and display in a html SharePoint Modal Dialog as Pie Chart.


Code Pie charts:

javascript:
    function DialogApps(element) {
        SP.UI.ModalDialog.showModalDialog({
            html: element,
            title: "Google Chart Example",
            allowMaximize: false,
            showClose: true,
            autoSize: true,
            height: 600,
            width: 600,
        });
    }

function drawStuff(array) {
    var data = new google.visualization.arrayToDataTable(array);

    var options = {
        title: 'Chart Example',
        width: 600,
        height: 600
        
    };
    var element = document.createElement('div');
    element.setAttribute("id", "top_x_div");
    var chart = new google.visualization.PieChart(element);
    chart.draw(data, options);
    DialogApps(element);
}

function ChartLoad() {
    google.charts.load('current', {'packages': ['bar','corechart']});
    google.charts.setOnLoadCallback(GetListItems);
}

function GetListItems() {
    var ctx = new SP.ClientContext.get_current();
    var targetList = ctx.get_web().get_lists().getById(SP.ListOperation.Selection.getSelectedList());
    var query = SP.CamlQuery.createAllItemsQuery();

    var queryResults = targetList.getItems(query);
    ctx.load(queryResults);

    ctx.executeQueryAsync(function getDocsAllItemsSuccess(sender, args) {
            var array = [];
            array.push(['Country', 'Sale']);
            var listEnumerator = queryResults.getEnumerator();
            while (listEnumerator.moveNext()) {
                array.push([listEnumerator.get_current().get_item("Title"), listEnumerator.get_current().get_item("Sales")]);
            }
            drawStuff(array);
        },
        function getDocsAllItemsFailure(sender, args) {
            alert('Failed to get list items. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
        });
}

SP.SOD.registerSod("Chart", "//www.gstatic.com/charts/loader.js");
SP.SOD.executeFunc('Chart', false, ChartLoad);
GetListItems();

Bar and Pie Charts in Modal Dialog

The Ribbon Custom Action "All Charts" read the List items from the Custom List and display in a html SharePoint Modal Dialog as Bar Chart and Pie Chart.


Code All charts:

javascript:
    function DialogApps(element) {
        SP.UI.ModalDialog.showModalDialog({
            html: element,
            title: "Google Chart Example",
            allowMaximize: false,
            showClose: true,
            autoSize: true,
            height: 650,
            width: 1200,
        });
    }

function drawStuff(array) {
    var data = new google.visualization.arrayToDataTable(array);

 var optionsPie = {
        title: 'Chart Example',
        width: 600,
        height: 600
        
    };
    var elementPie = document.createElement('div');
    elementPie.setAttribute("id", "top_Pie_div");
    var chartPie = new google.visualization.PieChart(elementPie);
    chartPie.draw(data, optionsPie);

    var optionsBar = {
        title: 'Chart Example',
        width: 600,
        height: 600,
        legend: {
            position: 'none'
        },
        chart: {
            subtitle: 'Sales by Country'
        },
         bars: 'horizontal',
        axes: {
            x: {
                0: {
                    side: 'top',
                    label: 'Sales'
                } 
            }
        },
        bar: {
            groupWidth: "90%"
        }
    };
    var elementBar = document.createElement('div');
    elementBar.setAttribute("id", "top_Bar_div");
    var chartBar = new google.charts.Bar(elementBar);
    chartBar.draw(data, google.charts.Bar.convertOptions(optionsBar));
    var element =  document.createElement('div');
    element.appendChild(elementBar);
    element.appendChild(elementPie);
    
    var x = document.createElement("TABLE");
    x.setAttribute("id", "myTable");

    var y = document.createElement("TR");
    y.setAttribute("id", "myTr");
    x.appendChild(y);

    var z = document.createElement("TD");
    z.appendChild(elementBar);
    y.appendChild(z);
    
    z = document.createElement("TD");
    z.appendChild(elementPie);
    y.appendChild(z);
    
    DialogApps(x);
}

function ChartLoad() {
    google.charts.load('current', {'packages': ['bar','corechart']});
    //google.charts.load('current', {'packages': ['bar']});
    google.charts.setOnLoadCallback(GetListItems);
}

function GetListItems() {
    var ctx = new SP.ClientContext.get_current();
    var targetList = ctx.get_web().get_lists().getById(SP.ListOperation.Selection.getSelectedList());
    var query = SP.CamlQuery.createAllItemsQuery();

    var queryResults = targetList.getItems(query);
    ctx.load(queryResults);

    ctx.executeQueryAsync(function getDocsAllItemsSuccess(sender, args) {
            var array = [];
            array.push(['Country', 'Sale']);
            var listEnumerator = queryResults.getEnumerator();
            while (listEnumerator.moveNext()) {
                array.push([listEnumerator.get_current().get_item("Title"), listEnumerator.get_current().get_item("Sales")]);
            }
            drawStuff(array);
        },
        function getDocsAllItemsFailure(sender, args) {
            alert('Failed to get list items. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
        });
}

SP.SOD.registerSod("Chart", "//www.gstatic.com/charts/loader.js");
SP.SOD.executeFunc('Chart', false, ChartLoad);
GetListItems();

After the creation of this example you are able to make more chart and integrated other type of content and display in custom Ribbon Actions.

I hope you like this article, 
Kind regards, 
Andre Lage
Post a Comment