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.


Sample Image


Sample Code

(function() {
    'use strict';
    var RELATEDRECORDS = 'sales'; // Field code of the Related Records field
    var SPACEFIELD = 'numberSpace'; // Element ID of the Space field

    // Field codes of the fields set for the Fetch Criteria of the Related Records field
    var FETCH_CRITERIA_A = 'contact_name'; // Field code of the field in this App
    var FETCH_CRITERIA_B = 'contact_name'; // Field code of the field in the datasource App

    kintone.events.on('app.record.detail.show', function(event) {
        // Get all records related to the related records field
        function fetchRecords(opt_Field, 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: opt_Field + ' 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(offset + limit, limit, allRecords);
                return allRecords;

        // Create query based on the Filter settings for the related records field
        var keyValue = event.record[FETCH_CRITERIA_A].value;
        var opt_Field = FETCH_CRITERIA_B + '=' + '"' + keyValue + '"';

        fetchRecords(opt_Field).then(function(records) {
            // Insert the total number of records into the Space field
            var num = records.length;
            var divTotalAmount = document.createElement('div');
            divTotalAmount.style.textAlign = 'center';
            divTotalAmount.style.fontSize = '16px';
            divTotalAmount.innerHTML = String(num) + ' related sale(s)';
            return event;


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
Please sign in to leave a comment.