Count table rows (conditional)

This sample code counts the number of rows in your table that have field values that match a value of your choice.
The counted rows are set inside other fields, when you save your record data.

Sample Image

tableconditional.gif

Sample Code

(function() {
    "use strict";

    //Match the right hand side, with the field codes in your app
    var TABLEDATA = "TableField"; //field code of the table
    var WEATHER = "WeatherField"; //field in your table that contains conditional values
    var SUNNYCOUNT = "SunnyCountField"; //field that will hold the number of rows that matched condition A
    var CLOUDYCOUNT = "CloudyCountField"; //field that will hold the number of rows that matched condition B
    var RAINYCOUNT = "RainyCountField"; //field that will hold the number of rows that matched condition C


    //Set events to run when the save button is clicked on the record create or edit page
    kintone.events.on(["app.record.create.submit","app.record.edit.submit"], function(eventobj) {

        //Count the number of rows in the table
        var num_of_rows = eventobj.record[TABLEDATA].value;
        var sunny_count = 0, cloudy_count = 0, rainy_count = 0;

        for (var i = 0; num_of_rows.length > i; i++) {
            var weather = num_of_rows[i].value[WEATHER].value;
            if (weather === 'Sunny') { //count fields with the value "Sunny"
                sunny_count++;
            } else if (weather === 'Cloudy') { //count fields with the value "Cloudy"
                cloudy_count++;
            } else if (weather === 'Rainy') { //count fields with the value "Rainy"
                rainy_count++;
            }
        }

        //Set the counts into the event object
        eventobj.record[SUNNYCOUNT].value = sunny_count;
        eventobj.record[CLOUDYCOUNT].value = cloudy_count;
        eventobj.record[RAINYCOUNT].value = rainy_count;

        //Return the event object, so that kintone will use this new data
        return eventobj;
    });
}());

 

Make sure to match the field codes stated for TABLEDATA, WEATHER, SUNNYCOUNT, CLOUDYCOUNT, RAINYCOUNT with the field codes in your app.

Refer to this page, on how to add scripts to your app.

Was this article helpful?
0 out of 0 found this helpful
Comments
Please sign in to leave a comment.