Snippets

Piotr Szrajber Smart M.App BI - Simple DataTable widget

Created by Piotr Szrajber last modified
//@ sourceURL=datatable.js

/**
* Simple DataTable widget created as a custom DC.js chart object.
* 
* It relies on bootstrap table class names (.table .table-hover .table-responsive)
* and dc.js dc.dataTable chart. There is an inconsistency in the DC.js API with
* the dc.dataTable.group method that DOES NOT EXPECT crossfilter group
* and the GVC libarary, which expects that every group is a crossfilter group must be prepared
* for this case. GVC versions older than 2017-01-25 will throw "key is not a function" error
*
* 2017-01-25 Piotr Szrajber <piotr.szrajber@hexagongeospatial.com>
*/
var SIZE = 3200;

gsp.bi.stage.requireLibraries(function(gvc, dc, d3, cf) {
    gsp.bi.stage.findStage(null, function(stage) {
        var stageModel = stage.stageModel(),
            propertyNames = [
                "NAME",
                "STATE_NAME",
                "Predicted_Crime_Index",
                "Poverty_Rate",
                "Unemployement_Rate",
                "Population_Increase_Ratio",
                "Average_Household_Size",
                "CI_Category_Text"
            ],
            columns = propertyNames.map(function(propertyName) {
                return function(d) {
                    return d[propertyName];
                }
            }),
            header = "<thead><tr>" + propertyNames.map(function(propertyName) {
                return "<th>" + propertyName + "</th>";
            }).join("") + "</tr></thead>";


        var table = document.createElement("table"),
            dcTable = dc.dataTable(table);
        dcTable.columns(columns);
        dcTable.size(SIZE);
        table.innerHTML = header;
        table.classList.add("table", "table-hover");
        table.style.backgroundColor = "#fff";
        table.style.color = "#000";
        dataTable = gvc.chart.base(dcTable);
        dataTable.group(function(d) {
            return d.key
        });
        dataTable.colors = function() {};

        gsp.bi.stage.addWidget({
            descriptor: {
                chartM: {
                    id: "tableChart",
                    name: "tableChart",
                    title: "Test chart",
                    key: stageModel.fields[0].id,
                    values: [stageModel.values[0].id]
                },
                chart: dataTable
            }
        }, function(success) {
            var container = document.getElementById("chart_1g6n").querySelector(".widget-chart");
            container.innerHTML = "";
            container.classList.add("table-responsive");
            container.appendChild(table);

        }, function(error) {
            console.error(error);
        });
    });
});

Comments (0)