Search code examples
jsfprimefacesprimefaces-extensions

How to specify column type in pe:gcharts


Simple question, but I can't come up with the answer.

In plain GCharts, I have this:

var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Value 1');
data.addColumn('number', 'Value 2');

However, how can I specify that the values are datetime and number with the model builder of PrimerFaces?

The .addColumns() method just adds the items as List<String>:

GChartModelBuilder lineChartModelBuilder = new GChartModelBuilder();
lineChartModelBuilder.setChartType(GChartType.LINE);    
lineChartModelBuilder.addColumns("Time");
lineChartModelBuilder.addColumns("Value 1");
lineChartModelBuilder.addColumns("Value 2");

Thank you!


Solution

  • I am assuming you are using a very old PF Extensions version? The reason I say that is back in 2016 this was fixed to use List<Object> instead of List<String> and was released in PrimeFaces Extensions 6.1 or higher.

    Latest version of the code can be seen here: https://github.com/primefaces-extensions/core/blob/master/src/main/java/org/primefaces/extensions/component/gchart/model/GChartModelBuilder.java

    Fixed back in 2016: https://github.com/primefaces-extensions/core/commit/6c473bbc50920bfdaedca02b918c29a5ead8d4d0#diff-f3a907dcc2d19626bf60db5bbebba6be

    Update:

    If you want to add the data using key value pairs it should be possible. Since GChart usese Google GSON to turn the Java code into JSON to the client i would think if you put a String array value in the field it would deserialize like you were expecting.

    Create a POJO representing the column:

    public class GChartModelColumn {
    
        // column label
        private final String label;
    
        // column type: number, date, datetime
        private final String type;
    
        public GChartModelColumn(String label, String type) {
            super();
            this.label = label;
            this.type = type;
        }
    
        public String getLabel() {
            return label;
        }
        public String getType() {
            return type;
        }
    }
    
    

    Then add the columns using the model above like...

    lineChartModelBuilder.addColumns(
    new GChartModelColumn("Time", "datetime"), 
    new GChartModelColumn("Value 1", "number"), 
    new GChartModelColumn("Value 2", "number"));
    

    Then in the JS code it converts your data object into a Google DataTable.

    var dataTable = google.visualization.arrayToDataTable(this.data);