Display total number of related records

The Related Records field in kintone is a useful field that lists other records that match a given condition. The Related Records field though does not state how many records it is listing - which may become hard to count manually when there are many records listed.

This sample code does the counting for you, and displays the number in a Space field of your App.
As shown in the image below, each record will display a different number for the total number of related records.

related1.PNG

Sample Image

related2.gif

Sample Code

(function() {
    "use strict";
    var RELATEDRECORDS = "sales";
    var SPACEFIELD = "numberSpace";

    kintone.events.on('app.record.detail.show', function(event) {
        //Get all records related to the related records field
        function fetchRecords(appId, opt_offset, opt_limit, opt_records) {
            var Id = kintone.app.getRelatedRecordsTargetAppId(RELATEDRECORDS);
            var offset = opt_offset || 0;
            var limit = opt_limit || 100;
            var allRecords = opt_records || [];
            var params = {app: Id, query: 'order by $id asc limit ' + limit + ' offset ' + offset};
            return kintone.api('/k/v1/records', 'GET', params).then(function(resp) {
                allRecords = allRecords.concat(resp.records);
                if (resp.records.length === limit) {
                    return fetchRecords(appId, offset + limit, limit, allRecords);
                }
                return allRecords;
            });
        }
        fetchRecords(kintone.app.getId()).then(function(records) {
            //Insert the total number of records into the Space field
            var num = records.length;
            var divTotalAmount = document.createElement('div');
            //divTotalAmount.style.fontWeight = 'bold';
            divTotalAmount.style.textAlign = 'center';
            divTotalAmount.style.fontSize = '16px';
            divTotalAmount.innerHTML = String(num) + ' related sale(s)';
            kintone.app.record.getSpaceElement(SPACEFIELD).appendChild(divTotalAmount);
            return event;
        });
    });
})();

Notes

Refer to the Tutorial page, on how to add scripts to your app.
Note that this sample will only display the number - it will not store and save the total number in a field.

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