none
Issue with Line chart

    General discussion

  • Hello Techies,

    I was trying to create line chart using CSR approach, for this I used highchart framework.
    I referred this link for line chart.
    Here is my list :

    Here is the code :

    /*
    Title: barCharts
    Description:This code can be used to create charts using Highcharts.js framework
    Author: Sachchin Annam
    */
    
    document.write('<script src="/imisscpl/dw/SiteAssets/Charts/highcharts.js"><\/script>')
    document.write('<script src="/imisscpl/dw/SiteAssets/Charts/exporting.js"><\/script>')
    
    
    // Declare the variables.
    var csrCharts = csrCharts || {};
     
    csrCharts.colors = ['#612ab3', '#c2242e', '#4876ff','#ffc125','#00406d','#fa3d0d','#cd3700','#ff8247'];
     
    csrCharts.ChartTitle =[];
    csrCharts.KKR = [];
    csrCharts.RCB = [];
    csrCharts.RR= [];
    csrCharts.CSK= [];
    csrCharts.MI= [];
    csrCharts.DC= [];
    csrCharts.KXIP= [];
    csrCharts.DD= [];
     
     
    csrCharts.Desc = '';
      
    // Override the rendering.
    csrCharts.FieldRenderSetup = function () {
      
        var override = {};
        override.Templates = {};
        override.Templates.Header = csrCharts.CustomHeader;
        override.Templates.Item = csrCharts.CustomItem;
        override.Templates.Footer = csrCharts.CustomFooter;
      
        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(override);
    };
    
     
    csrCharts.CustomItem = function (ctx) {
        csrCharts.ChartTitle.push(ctx.CurrentItem.Title);//columns names
        csrCharts.KKR.push(parseInt(ctx.CurrentItem.KKR));//columns names
        csrCharts.RCB.push(parseInt(ctx.CurrentItem.RCB));//columns names
        csrCharts.CSK.push(parseInt(ctx.CurrentItem.CSK));//columns names
        csrCharts.RR.push(parseInt(ctx.CurrentItem.RR));//columns names
        csrCharts.MI.push(parseInt(ctx.CurrentItem.MI));//columns names
        csrCharts.DC.push(parseInt(ctx.CurrentItem.DC));//columns names
        csrCharts.KXIP.push(parseInt(ctx.CurrentItem.KXIP));//columns names
        csrCharts.DD.push(parseInt(ctx.CurrentItem.DD));//columns names
    
        return '';
    }
    
    csrCharts.CustomHeader = function (ctx) {
        return "<div id='container'></div>";
    }
    
    
    // Override the footer.
    csrCharts.CustomFooter = function () {
      debugger;
      var colors = Highcharts.getOptions().colors;
    colors = ['#612ab3', '#c2242e', '#4876ff','#ffc125','#00406d','#fa3d0d','#cd3700','#ff8247'];
    
    Highcharts.chart('container', {
    
        
        title: {
            text: 'IPL Statistics'
        },
        subtitle: {
            text: 'Season1-5'
        },
       
          yAxis: {
            title: {
                text: 'Number of Employees'
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
        },
    
        plotOptions: {
            series: {
                pointStart:csrCharts.ChartTitle[0],
            }
        },    series: [{
            name: 'KKR',
            data: csrCharts.KKR,
            color:colors[0]
    
        }, {
            name: 'RCB',
            data: csrCharts.RCB,
            color:colors[1]
    
        }, {
            name: 'RR',
            data: csrCharts.RR,
            color:colors[2]
    
        }, {
            name: 'CSK',
            data: csrCharts.CSK,
            color:colors[3]
    
        },{
            name: 'MI',
            data: csrCharts.MI,
            color:colors[4]
    
        },{
            name: 'DC',
            data: csrCharts.DC,
            color:colors[5]
        },{
            name: 'KXIP',
            data: csrCharts.KXIP,
            color:colors[6]
        },{
            name: 'DD',
            data: csrCharts.DD,
            color:colors[7]
        }
    
        
        ]
    });
    return '';
    
    }
    
    $(document).ready(csrCharts.FieldRenderSetup());
    
    

    And here is the Output :

    I tried to debug the code and able to data in array but don't what's going wrong in the code.
    Please help me

    Friday, April 21, 2017 8:39 AM

All replies

  • Hi,

    I have created the list with following schema:

    Added following items:

    After that created the page added following references on SharePoint page using script editor web part:

    <!-- ### Chart HTML.::Start::---- ### -->
    
    <div>
        <!-- ### JavaScript JS Add-ons Modules.::Start::---- ### -->
        <script type="text/javascript" src="/sites/amitkumarmca04_blogspot_com/SiteAssets/jquery-3.1.1.min.js"></script>
        <script type="text/javascript" src="/sites/amitkumarmca04_blogspot_com/SiteAssets/CreateChart.js"></script>
        <!-- ### JavaScript JS Add-ons Modules.::End::---- ### -->
        <!-- ### JQury Highchards JS Add-ons Modules.::Start::---- ### -->
        <script src="https://code.highcharts.com/highcharts.js"></script>
        <script src="https://code.highcharts.com/modules/exporting.js"></script>
        <!-- ### JQury Highchards JS Add-ons Modules.::End::---- ### -->
    
        <style>
            #container {
    	min-width: 310px;
    	max-width: 800px;
    	height: 400px;
    	margin: 0 auto
    }
        </style>
    
        <div id="container"></div>
    
    
    
    </div>
    <!-- ### Chart HTML.::Start::---- ### -->
    

    The code of CreateChart.js is:

    /****************************************************************************
    Sample.CreateChart.js provide functionality for access CreateChart.js JS-Addon.
    *****************************************************************************/
    /* 
    * Version:       0.0.0.5
    * Created By:   Amit Kumar
    * CreatedDate:   04/21/2017 (MM/DD/YYYY)
    * Modified By:  Amit Kumar
    * ChangeDate:   04/21/2017 (MM/DD/YYYY)
    */
    var Sample = {};
    
    Sample.CreateChart = {
        ConfigLists: {},
        Config_List_Data: []
        , FieldCollection: []
        ,IS_TESTING_ENABLED: true
    
        /*
          This function has been used to write message on console
          */
        , WriteMessage: function (message) {
            if (typeof console != 'undefined') {
                console.log(message);
            }
        }
    
        /*
        This function has been used to write error message on console
        */
        , WriteErrorMessage: function (message) {
            Sample.CreateChart.WriteMessage('Error=>' + message);
        }
    
        /*
        This function has been used to write message on console including DATETIME
        */
       , WriteTestMessage: function (message) {
           if (Sample.CreateChart.IS_TESTING_ENABLED) {
               Sample.CreateChart.WriteMessage('[' + new Date().toUTCString() + '] => ' + message);
           }
       }
        /*
      This function has been used to set the configuration data required
      on initial load of page.
      */
       , ConfigureData: function () {
           Sample.CreateChart.Config_List_Data = [];
    
           Sample.CreateChart.ConfigLists["ScoreList"] = {
               ListId: '2A059A17-487E-4CC0-8E79-73F63926D542',
               ListTitle: 'ScoreList',
               Columns: [
                                { displayName: 'Id', InernalName: "ID", Id: "Id", FieldType: "Number" },
                                { displayName: 'Title', InernalName: "Title", Id: "Title", FieldType: "Text" },
                                { displayName: 'KKR', InernalName: "KKR", Id: "Value", FieldType: "Number" },
                                { displayName: 'RCB', InernalName: "RCB", Id: "Value", FieldType: "Number" }
            ]
           };
       }
    
    
        ,IsNullOrEmpty : function (value) {
        if (value == null || typeof (value) == 'undefined' || value == '')
            return true;
        else
            return false;
    }
            /*
        This function has been used to set the list items in the form of object
        on the basis of columns present in the ConfigLists object for particular list
        */
        , ListItemsLoaded: function (itemsLoadResult) {
            var flatList = [];
    
            var enumerator = itemsLoadResult.Items.getEnumerator();
            var columns;
            // get corresponding columns for the given list ID
            for (var conf in Sample.CreateChart.ConfigLists) {
                if (Sample.CreateChart.ConfigLists[conf].ListId == itemsLoadResult.ListId) {
                    columns = Sample.CreateChart.ConfigLists[conf].Columns;
                }
            }
    
            while (enumerator.moveNext()) {
                var currentListItem = enumerator.get_current();
                var resultJson = {};
                // Helper to identify column type of the list item
                var toClass = {}.toString // (1)	
                var objListItem;
                var listData = [];
    
                for (var i = 0; i < columns.length; i++) {
                    var columnValue = "";
                    try {
                        // Check if property exists to prevent exceptions
                        var column = currentListItem.get_item(columns[i].InernalName);
                        var columnType = toClass.call(column);
                        // only identifable indicator for an lookup column ([object (SP.FieldLookupValue)])
                        if (columnType == '[object Object]') {
                            columnValue = column.get_lookupValue();
                            // in addition to the "normal" columns, also save the underlying lookup ID to allow joining
                            resultJson[columns[i] + 'Id'] = column.get_lookupId();
                        } else {
                            columnValue = column;
                        }
                        resultJson[columns[i].InernalName] = columnValue;
                    } catch (err) {
                        Sample.CreateChart.WriteErrorMessage("Sample.CreateChart.ListItemsLoaded :: Error while getting column '" + columns[i].FieldName + "', Error: " + err.toString());
                    }
                }
                flatList.push(resultJson);
            }
            return flatList;
        }
    
        /*
        This function has been used to get the data from Config list using JSOM without where clause
        */
        , GetScoreListData: function (listTitle, listId) {
            var deferred = $.Deferred();
    
            var clientContext = new SP.ClientContext.get_current(); 
    
            var website = clientContext.get_web();
            var oList = clientContext.get_web().get_lists().getByTitle(listTitle);
    
            var query = new SP.CamlQuery(); //The Query object. This is used to query for data in the List
    
            var camlQuery = "";
    
    
            camlQuery = "<View><\/View>";
            query.set_viewXml(camlQuery);
    
            var items = oList.getItems(query);
    
            clientContext.load(website);
            clientContext.load(oList);
            clientContext.load(items);
    
            clientContext.executeQueryAsync(
                    Function.createDelegate(this, function () {
                        var result = {};
                        result["ListId"] = listId;
                        result["Items"] = items;
                        // extract all columns for all items and build objects out of it => override items property with transformed data
                        result["Items"] = Sample.CreateChart.ListItemsLoaded(result);
                        deferred.resolve(result);
                    }),
            Function.createDelegate(this, function (sender, args) {
                deferred.reject('Request failed. ' + args.get_message());
                CreateChart.WriteErrorMessage('Sample.CreateChart.GetConfigListData :: Request failed. ' + args.get_message() + ', StackTrace:' + args.get_stackTrace());
            })
               );
    
            return deferred.promise();
        }
    
    
        , GetUniqueDetailsFromObject: function (input, uniqueItem) {
            var lookup = {};
            var items = input;
            var result = [];
            var name = '';
            for (var item, i = 0; item = items[i++];) {
    
                switch (uniqueItem.toLowerCase()) {
                    case 'kkr':
                        name = item.KKR;
                        break;
                    case 'rcb':
                        name = item.RCB;
                        break;
                }
    
    
                if (!(name in lookup)) {
                    lookup[name] = 1;
                    result.push(name);
                }
            }
            return result; //array of unique items
        }
    
        ,CreateChartOnPage : function()
        {
    
            var arrSeries = []
    
            var objSeries = null;
    
            for (var i = 0; i < Sample.CreateChart.ConfigLists["ScoreList"].Columns.length; i++) {
                if (Sample.CreateChart.ConfigLists["ScoreList"].Columns[i].InernalName != "ID"
                    && Sample.CreateChart.ConfigLists["ScoreList"].Columns[i].InernalName != "Title"
                    )
                    {
                        objSeries = null;
                        objSeries = new Object();
                        objSeries.name = Sample.CreateChart.ConfigLists["ScoreList"].Columns[i].displayName;
                        objSeries.data = Sample.CreateChart.GetUniqueDetailsFromObject(Sample.CreateChart.Config_List_Data, Sample.CreateChart.ConfigLists["ScoreList"].Columns[i].InernalName);
                        arrSeries.push(objSeries);
                     }
            }
    
            Highcharts.chart('container', {
    
                title: {
                    text: 'IPL Statistics'
                },
    
                subtitle: {
                    text: 'Session 1-5'
                },
    
                yAxis: {
                    title: {
                        text: 'Number of Employees'
                    }
                },
                legend: {
                    layout: 'vertical',
                    align: 'right',
                    verticalAlign: 'middle'
                },
    
                plotOptions: {
                    series: {
                        pointStart: 2010
                    }
                },
    
                series: arrSeries
                /*
                series: [{
                    name: 'Installation',
                    data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
                }, {
                    name: 'Manufacturing',
                    data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
                }, {
                    name: 'Sales & Distribution',
                    data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
                }, {
                    name: 'Project Development',
                    data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
                }, {
                    name: 'Other',
                    data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
                }]
                */
    
            });
    
        }
    
        /*
      This function has been used to call functions, which required to fill 
      configuration data and data required on page load
      */
        ,Init: function () {
    
            //--Configure required data
            Sample.CreateChart.ConfigureData();
    
                var loadingDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Loading...', 'Please wait while request is in progress...', 150, 400);
    
                //--Now get data from Config List----::Start::----------//
                var pConfig = Sample.CreateChart.GetScoreListData(Sample.CreateChart.ConfigLists["ScoreList"].ListTitle, Sample.CreateChart.ConfigLists["ScoreList"].ListId);
                pConfig.done(function (result) {
                    try {
                        // result is an SP.List because that is what we passed to resolve()!
                        var list = result;
                        Sample.CreateChart.Config_List_Data = null;
                        if (!Sample.CreateChart.IsNullOrEmpty(list) && list.Items.length > 0) {
                            Sample.CreateChart.Config_List_Data = [];
                            Sample.CreateChart.Config_List_Data = list.Items;
    
                            Sample.CreateChart.CreateChartOnPage();
                        }
                    }
                    catch (err) {
                        Sample.CreateChart.WriteErrorMessage("Sample.CreateChart.Init > Catch :: " + err.toString());
                    } finally {
                        loadingDialog.close();
                    }
    
                });
                pConfig.fail(function (result) {
                    // result is a string because that is what we passed to reject()!
                    var error = result;
                    Sample.CreateChart.WriteErrorMessage("Sample.CreateChart.Init > p.fail :: " + error);
                    loadingDialog.close();
                });
    
            //--Now get data from Config List----::Start::----------//
    
        }
    
        /*
        This function has been used to call INIT function, when all required SharePoint JS add-ons loaded on page
        */
        ,Start : function(){
            // to support synchronous and asynchronous updates of the site first load all scripts and finally execute functions if scripts are loaded
            // sequentially load all relevant scripts
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){});
            SP.SOD.executeFunc('sp.runtime.js', null, function(){});
            SP.SOD.executeFunc('init.js', null, function(){});
            SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.ClientContext', function(){});
    		
            // nested checks, if relevant scripts are already loaded
            ExecuteOrDelayUntilScriptLoaded(function(){
                ExecuteOrDelayUntilScriptLoaded(function(){
                    ExecuteOrDelayUntilScriptLoaded(function(){
                        ExecuteOrDelayUntilScriptLoaded(Sample.CreateChart.Init, "sp.ui.dialog.js");
                    },"init.js");
                },"sp.runtime.js");
            }, "sp.js");
    
        }
    
        /*
        This function has been used to call function on Document.Ready
        */
     	,DocumentLoaded: function () {
     	    SP.SOD.loadMultiple(['sp.js', 'sp.runtime.js', 'strings.js', 'init.js', 'sp.ui.dialog.js'], Sample.CreateChart.Start);
     	}
    
    };
    
    //-----------Document.Ready----::Start::------------------//
    $(document).ready(function () {
        Sample.CreateChart.DocumentLoaded();
    });
    //-----------Document.Ready----::End::------------------//

    With the help of above code HighChart being rendered on SharePoint page:

        Please try above code in SharePoint page and let me know, if you required any help on this.


    Thanks, Amit Kumar, LinkedIn Profile ** My Blog
    Please click "Mark As Answer" if this post solves your problem or "Vote As Helpful" if it was useful

    Friday, April 21, 2017 2:00 PM
  • Thanks Amit for your response. I need to achieve this through jslink. Please let me know is  there something i am missing in my code ?
    • Edited by Sachchin Friday, April 21, 2017 4:58 PM
    Friday, April 21, 2017 4:54 PM
  • Hi Sachchin,

    In which out of the box form (View/Display/Add/Edit) , you are trying to use JSLink.

    Thanks, Amit Kumar, LinkedIn Profile ** My Blog
    Please click "Mark As Answer" if this post solves your problem or "Vote As Helpful" if it was useful


    Monday, April 24, 2017 7:21 AM
  • Hi Sachchin,

    I have converted above mentioned JS into JSLink and performing following operations in JSLink:

    1. On Pre-render event, i am trying to add reference of JQuery/Highchartjs:

    JSLinkSecurity.OnPreRender = JSLinkSecurity.Functions.InitiateScopeList;

    In the InitiateScopeList function, i am calling JSLinkSecurity.Functions.AddJQuery function:

    JSLinkSecurity.Functions.AddJQuery = function (ctx) {
        absoluteSiteUrl = _spPageContextInfo.webAbsoluteUrl;
    
        var siteUrl = window.location.protocol + "//" + window.location.host + "/"; //=>
        // check if jQuery is available, otherwise reload it
        if (!window.jQuery) {
            var jq = document.createElement('script'); jq.type = 'text/javascript';
            jq.src = siteUrl + JQuery_URL;
            document.getElementsByTagName('head')[0].appendChild(jq);
        }
    
        if (!window.Highcharts) {
            var hCJS = document.createElement('script'); hCJS.type = 'text/javascript';
            hCJS.src = HighJS_URL;
            document.getElementsByTagName('head')[0].appendChild(hCJS);
    
            //---Check pop-up html loaded or not----::Start::--------------
            var chkHCJS = setInterval(function () {
                if (window.Highcharts) {
    
                    var hCEJS = document.createElement('script'); hCEJS.type = 'text/javascript';
                    hCEJS.src = ExportJS_URL;
                    document.getElementsByTagName('head')[0].appendChild(hCEJS);
    
    
    
                    clearInterval(chkHCJS);
                }
            }, 300);
            //---Check pop-up html loaded or not----::Start::--------------
    
        }
    
        JSLinkSecurity.Functions.DocumentLoaded();
    
    }
    After adding the references of required JS Add-ons, i am calling function JSLinkSecurity.Functions.DocumentLoaded, to get the data from list, which used later point to render the chard.

    2. Currently i am overriding Footer template in View form of list: 

    JSLinkSecurity.Templates.Footer = '<div id="container"></div>';

    In the above code block, i am adding container for HightChart, which will be used later to render the chart.

    The output is:

    Complete code for your reference:

    /* This Script can be reference via the List Property of a WebPart to display chart
    * Version:      0.0.1.1
    * Created By:   Amit Kumar
    * Modified By:  Amit Kumar
    * ChangeDate:   04/24/2017 (MM/DD/YYYY)
    */
    
    //----------Declare and Initialze global variables----------::Start::--------------
    var CURRENT_CONTEXT = '';
    var CURRENT_WEB = '';
    var SP_LIST = '';
    var JSLink_URL = "/SiteAssets/JSLink_Chart.js";
    var JQuery_URL = 'sites/amitkumarmca04_blogspot_com/SiteAssets/jquery-3.1.1.min.js';
    var HighJS_URL = 'https://code.highcharts.com/highcharts.js';
    var ExportJS_URL = 'https://code.highcharts.com/modules/exporting.js';
    var CURRENT_FIELD_VALUE = '';
    var CURRENT_FIELD_ID = '';
    var CURRENT_LIST_TITLE = '';
    var CURRENT_LIST_TITLE = '';
    
    
    //----------Declare and Initialze global variables----------::Start::--------------
    
    Type.registerNamespace('JSLinkSecurity')
    JSLinkSecurity.Templates = JSLinkSecurity.Templates || {}
    JSLinkSecurity.Functions = JSLinkSecurity.Functions || {}
    
    JSLinkSecurity.ConfigLists = {};
    JSLinkSecurity.Config_List_Data= [];
    JSLinkSecurityFieldCollection= [];
    JSLinkSecurity.IS_TESTING_ENABLED = true;
    
    
    JSLinkSecurity.Functions.HideFields = function (ctx) {
        if (ctx != null) {
            var chkDefaultValue = setInterval(function () {
                if ($('.csrHide').length != 0) {
    
                    $('.csrHide').hide();
                    clearInterval(chkDefaultValue);
    
                    
                }
            }, 100);
        }
    }
    
    /*
      This function has been used to write message on console
      */
    JSLinkSecurity.Functions.WriteMessage= function (message) {
            if (typeof console != 'undefined') {
                console.log(message);
            }
        }
    
    
        /*
        This function has been used to write error message on console
        */
    JSLinkSecurity.Functions.WriteErrorMessage= function (message) {
        JSLinkSecurity.Functions.WriteMessage('Error=>' + message);
    }
    
        /*
        This function has been used to write message on console including DATETIME
        */
    JSLinkSecurity.Functions.WriteTestMessage= function (message) {
        if (JSLinkSecurity.Functions.IS_TESTING_ENABLED) {
               JSLinkSecurity.Functions.WriteMessage('[' + new Date().toUTCString() + '] => ' + message);
           }
       }
    
    
        /*
      This function has been used to set the configuration data required
      on initial load of page.
      */
    JSLinkSecurity.Functions.ConfigureData= function () {
        JSLinkSecurity.Config_List_Data = [];
    
        JSLinkSecurity.ConfigLists["ScoreList"] = {
               ListId: '2A059A17-487E-4CC0-8E79-73F63926D542',
               ListTitle: 'ScoreList',
               Columns: [
                                { displayName: 'Id', InernalName: "ID", Id: "Id", FieldType: "Number" },
                                { displayName: 'Title', InernalName: "Title", Id: "Title", FieldType: "Text" },
                                { displayName: 'KKR', InernalName: "KKR", Id: "Value", FieldType: "Number" },
                                { displayName: 'RCB', InernalName: "RCB", Id: "Value", FieldType: "Number" }
               ]
           };
    }
    
    JSLinkSecurity.Functions.IsNullOrEmpty =function (value) {
            if (value == null || typeof (value) == 'undefined' || value == '')
                return true;
            else
                return false;
        }
    
    
            /*
        This function has been used to set the list items in the form of object
        on the basis of columns present in the ConfigLists object for particular list
        */
    JSLinkSecurity.Functions.ListItemsLoaded= function (itemsLoadResult) {
            var flatList = [];
    
            var enumerator = itemsLoadResult.Items.getEnumerator();
            var columns;
            // get corresponding columns for the given list ID
            for (var conf in JSLinkSecurity.ConfigLists) {
                if (JSLinkSecurity.ConfigLists[conf].ListId == itemsLoadResult.ListId) {
                    columns = JSLinkSecurity.ConfigLists[conf].Columns;
                }
            }
    
            while (enumerator.moveNext()) {
                var currentListItem = enumerator.get_current();
                var resultJson = {};
                // Helper to identify column type of the list item
                var toClass = {}.toString // (1)	
                var objListItem;
                var listData = [];
    
                for (var i = 0; i < columns.length; i++) {
                    var columnValue = "";
                    try {
                        // Check if property exists to prevent exceptions
                        var column = currentListItem.get_item(columns[i].InernalName);
                        var columnType = toClass.call(column);
                        // only identifable indicator for an lookup column ([object (SP.FieldLookupValue)])
                        if (columnType == '[object Object]') {
                            columnValue = column.get_lookupValue();
                            // in addition to the "normal" columns, also save the underlying lookup ID to allow joining
                            resultJson[columns[i] + 'Id'] = column.get_lookupId();
                        } else {
                            columnValue = column;
                        }
                        resultJson[columns[i].InernalName] = columnValue;
                    } catch (err) {
                        JSLinkSecurity.Functions.WriteErrorMessage("Sample.CreateChart.ListItemsLoaded :: Error while getting column '" + columns[i].FieldName + "', Error: " + err.toString());
                    }
                }
                flatList.push(resultJson);
            }
            return flatList;
        }
    
        /*
        This function has been used to get the data from Config list using JSOM without where clause
        */
    JSLinkSecurity.Functions.GetScoreListData= function (listTitle, listId) {
            var deferred = $.Deferred();
    
            var clientContext = new SP.ClientContext.get_current(); 
    
            var website = clientContext.get_web();
            var oList = clientContext.get_web().get_lists().getByTitle(listTitle);
    
            var query = new SP.CamlQuery(); //The Query object. This is used to query for data in the List
    
            var camlQuery = "";
    
    
            camlQuery = "<View><\/View>";
            query.set_viewXml(camlQuery);
    
            var items = oList.getItems(query);
    
            clientContext.load(website);
            clientContext.load(oList);
            clientContext.load(items);
    
            clientContext.executeQueryAsync(
                    Function.createDelegate(this, function () {
                        var result = {};
                        result["ListId"] = listId;
                        result["Items"] = items;
                        // extract all columns for all items and build objects out of it => override items property with transformed data
                        result["Items"] = JSLinkSecurity.Functions.ListItemsLoaded(result);
                        deferred.resolve(result);
                    }),
            Function.createDelegate(this, function (sender, args) {
                deferred.reject('Request failed. ' + args.get_message());
                JSLinkSecurity.Functions.WriteErrorMessage('Sample.CreateChart.GetConfigListData :: Request failed. ' + args.get_message() + ', StackTrace:' + args.get_stackTrace());
            })
               );
    
            return deferred.promise();
        }
    
    JSLinkSecurity.Functions.GetUniqueDetailsFromObject= function (input, uniqueItem) {
            var lookup = {};
            var items = input;
            var result = [];
            var name = '';
            for (var item, i = 0; item = items[i++];) {
    
                switch (uniqueItem.toLowerCase()) {
                    case 'kkr':
                        name = item.KKR;
                        break;
                    case 'rcb':
                        name = item.RCB;
                        break;
                }
    
    
                if (!(name in lookup)) {
                    lookup[name] = 1;
                    result.push(name);
                }
            }
            return result; //array of unique items
        }
    
    JSLinkSecurity.Functions.CreateChartOnPage = function()
        {
    
            var arrSeries = []
    
            var objSeries = null;
    
            for (var i = 0; i < JSLinkSecurity.ConfigLists["ScoreList"].Columns.length; i++) {
                if (JSLinkSecurity.ConfigLists["ScoreList"].Columns[i].InernalName != "ID"
                    && JSLinkSecurity.ConfigLists["ScoreList"].Columns[i].InernalName != "Title"
                    )
                {
                    objSeries = null;
                    objSeries = new Object();
                    objSeries.name = JSLinkSecurity.ConfigLists["ScoreList"].Columns[i].displayName;
                    objSeries.data = JSLinkSecurity.Functions.GetUniqueDetailsFromObject(JSLinkSecurity.Config_List_Data, JSLinkSecurity.ConfigLists["ScoreList"].Columns[i].InernalName);
                    arrSeries.push(objSeries);
                }
            }
    
            Highcharts.chart('container', {
    
                title: {
                    text: 'IPL Statistics'
                },
    
                subtitle: {
                    text: 'Session 1-5'
                },
    
                yAxis: {
                    title: {
                        text: 'Number of Employees'
                    }
                },
                legend: {
                    layout: 'vertical',
                    align: 'right',
                    verticalAlign: 'middle'
                },
    
                plotOptions: {
                    series: {
                        pointStart: 2010
                    }
                },
    
                series: arrSeries
    
            });
    
        }
    
    /*
    This function has been used to call functions, which required to fill 
    configuration data and data required on page load
    */
    JSLinkSecurity.Functions.Init= function () {
    
            //--Configure required data
        JSLinkSecurity.Functions.ConfigureData();
    
            var loadingDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Loading...', 'Please wait while request is in progress...', 150, 400);
    
            //--Now get data from Config List----::Start::----------//
            var pConfig = JSLinkSecurity.Functions.GetScoreListData(JSLinkSecurity.ConfigLists["ScoreList"].ListTitle, JSLinkSecurity.ConfigLists["ScoreList"].ListId);
            pConfig.done(function (result) {
                try {
                    // result is an SP.List because that is what we passed to resolve()!
                    var list = result;
                    JSLinkSecurity.Config_List_Data = null;
                    if (!JSLinkSecurity.Functions.IsNullOrEmpty(list) && list.Items.length > 0) {
                        JSLinkSecurity.Config_List_Data = [];
                        JSLinkSecurity.Config_List_Data = list.Items;
    
                        //---Check pop-up html loaded or not----::Start::--------------
                        var chkChartDIV = setInterval(function () {
                            if ($("#container").length > 0) {
                                JSLinkSecurity.Functions.CreateChartOnPage();
    
                                clearInterval(chkChartDIV);
                            }
                        }, 300);
                        //---Check pop-up html loaded or not----::Start::--------------
    
                        
                    }
                }
                catch (err) {
                    JSLinkSecurity.Functions.WriteErrorMessage("Sample.CreateChart.Init > Catch :: " + err.toString());
                } finally {
                    loadingDialog.close();
                }
    
            });
            pConfig.fail(function (result) {
                // result is a string because that is what we passed to reject()!
                var error = result;
                JSLinkSecurity.Functions.WriteErrorMessage("Sample.CreateChart.Init > p.fail :: " + error);
                loadingDialog.close();
            });
    
            //--Now get data from Config List----::Start::----------//
    
        }
    
    
    
        /*
        This function has been used to call INIT function, when all required SharePoint JS add-ons loaded on page
        */
    JSLinkSecurity.Functions.Start = function(){
            // to support synchronous and asynchronous updates of the site first load all scripts and finally execute functions if scripts are loaded
            // sequentially load all relevant scripts
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){});
            SP.SOD.executeFunc('sp.runtime.js', null, function(){});
            SP.SOD.executeFunc('init.js', null, function(){});
            SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.ClientContext', function(){});
    		
            // nested checks, if relevant scripts are already loaded
            ExecuteOrDelayUntilScriptLoaded(function(){
                ExecuteOrDelayUntilScriptLoaded(function(){
                    ExecuteOrDelayUntilScriptLoaded(function(){
                        ExecuteOrDelayUntilScriptLoaded(JSLinkSecurity.Functions.Init, "sp.ui.dialog.js");
                    },"init.js");
                },"sp.runtime.js");
            }, "sp.js");
    
        }
    
    
        /*
        This function has been used to call function on Document.Ready
        */
    JSLinkSecurity.Functions.DocumentLoaded= function () {
        SP.SOD.loadMultiple(['sp.js', 'sp.runtime.js', 'strings.js', 'init.js', 'sp.ui.dialog.js'], JSLinkSecurity.Functions.Start);
     	}
    
    JSLinkSecurity.Functions.LoadJSCSSFile = function (filename, filetype) {
        if (filetype == "js") { //if filename is a external JavaScript file
            var fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", filename)
        }
        if (typeof fileref != "undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref)
    }
    
    /*
    This function has been used to add reference of JQuery framework, if not present
    */
    JSLinkSecurity.Functions.AddJQuery = function (ctx) {
        absoluteSiteUrl = _spPageContextInfo.webAbsoluteUrl;
    
        var siteUrl = window.location.protocol + "//" + window.location.host + "/"; //=>
        // check if jQuery is available, otherwise reload it
        if (!window.jQuery) {
            var jq = document.createElement('script'); jq.type = 'text/javascript';
            jq.src = siteUrl + JQuery_URL;
            document.getElementsByTagName('head')[0].appendChild(jq);
        }
    
        if (!window.Highcharts) {
            var hCJS = document.createElement('script'); hCJS.type = 'text/javascript';
            hCJS.src = HighJS_URL;
            document.getElementsByTagName('head')[0].appendChild(hCJS);
    
            //---Check pop-up html loaded or not----::Start::--------------
            var chkHCJS = setInterval(function () {
                if (window.Highcharts) {
    
                    var hCEJS = document.createElement('script'); hCEJS.type = 'text/javascript';
                    hCEJS.src = ExportJS_URL;
                    document.getElementsByTagName('head')[0].appendChild(hCEJS);
    
    
    
                    clearInterval(chkHCJS);
                }
            }, 300);
            //---Check pop-up html loaded or not----::Start::--------------
    
        }
    
        JSLinkSecurity.Functions.DocumentLoaded();
    
    }
    
    /*
    This function has been called from the FIELDS and 
    >using AddJQuery function to add Jquery reference
    */
    JSLinkSecurity.Functions.InitiateScopeList = function () {
        //Add jqery and links
        JSLinkSecurity.Functions.AddJQuery(ctx);
    }
    
    
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //**********************Minimal Download Strategy(MDS) code block and JSLink code block**************::Start::***************
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    /*
    This function OnPreRender event fires before the DOM is loaded. 
    >using InitiateScopeList function
    */
    JSLinkSecurity.OnPreRender = JSLinkSecurity.Functions.InitiateScopeList;
    JSLinkSecurity.OnPostRender = JSLinkSecurity.Functions.HideFields;
    
    /*
    This function has been used to override the content of list view form for First Name field
    */
    JSLinkSecurity.Functions.CustomItem = function (ctx) {
        var result = '';
    
        if (ctx != null && ctx.CurrentItem != null) {
            result = "<span class='csrHide'>" + ctx.CurrentItem.FirstName + "</span>";
            return result;
        }
    }
    
    
    JSLinkSecurity.Templates.Footer = '<div id="container"></div>';
    
    //JSLinkSecurity.Templates.Item = JSLinkSecurity.Functions.CustomItem;
    
    /*
    This function has been used to register the namespace as per Minimal Download Strategy(MDS)
    */
    JSLinkSecurity.Functions.RegisterField = function () {
        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(JSLinkSecurity)
    }
    
    /*
    This function has been used to register the JS file as per Minimal Download Strategy(MDS)
    */
    JSLinkSecurity.Functions.MdsRegisterField = function () {
        var thisUrl = _spPageContextInfo.webServerRelativeUrl + JSLink_URL;
        JSLinkSecurity.Functions.RegisterField();
        RegisterModuleInit(thisUrl, JSLinkSecurity.Functions.RegisterField)
    }
    
    /*
    This code block used to find Minimal Download Strategy(MDS) enabled on the site or not
    >on the basis of that it's registring the JS file
    */
    if (typeof _spPageContextInfo != "undefined" && _spPageContextInfo != null) {
        //-- MDS enabled on our site
        JSLinkSecurity.Functions.MdsRegisterField()
    } else {
        //-- MDS no enabled on our site
        JSLinkSecurity.Functions.RegisterField()
    }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //**********************Minimal Download Strategy(MDS) code block and JSLink code block**************::End::***************
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    
    
    
    
    
    
    

        Please try above code in View form of list and let me know, if you required any help on this.


    Thanks, Amit Kumar, LinkedIn Profile ** My Blog
    Please click "Mark As Answer" if this post solves your problem or "Vote As Helpful" if it was useful

    Monday, April 24, 2017 8:32 AM
  • thanks Amit it worked. :) 
    Wednesday, April 26, 2017 9:47 AM