Insert Row Numbers Into Tables

Contents

Overview

This article introduces how to automatically insert row numbers into tables when the record is saved.

Sample Image

An event is triggered when the user navigates to the Record create page, navigates to the Record edit page, or makes changes to the Table field. This disables the Number field. An event is also triggered when the record is saved. The number of rows in the Table field is calculated, and the Number field is automatically filled in with row numbers.

Prepare the App

Create an App (External link) with the following fields and settings.

Field Type Field Name Field Code Notes
Table User List usertable See the table below for the fields to place inside.

Set the following fields and settings for the User List table.

Field Type Field Name Field Code
Number Row Number row_number
Text Name name

Sample Code

Prepare the following JavaScript code in a text editor and navigate to the Kintone App's settings. Upload the file into the Upload JavaScript for PC option of the JavaScript and CSS Customization settings (External link) .

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
(function() {
  'use strict';

  var TABLEFIELD = 'usertable'; // Field code of the table
  var NUMBERFIELD = 'row_number'; // Field code of number field in the table

  // Disable number fields in table at these events
  var disableEvents = [
    'app.record.edit.show',
    'app.record.create.show',
    'app.record.edit.change.' + TABLEFIELD,
    'app.record.create.change.' + TABLEFIELD
  ];

  kintone.events.on(disableEvents, function(event) {
    var record = event.record;

    // Disable number fields in table rows
    var count = record[TABLEFIELD].value.length;
    for (var i = 0; i < count; i++) {
      record[TABLEFIELD].value[i].value[NUMBERFIELD].disabled = true;
    }

    return event;
  });
  // Number table rows at these events
  var numberEvents = [
    'app.record.create.submit',
    'app.record.edit.submit'
  ];
  kintone.events.on(numberEvents, function(event) {
    var record = event.record;
    // Auto-number the table rows
    var count = record[TABLEFIELD].value.length;
    for (var i = 0; i < count; i++) {
      record[TABLEFIELD].value[i].value[NUMBERFIELD].value = i + 1;
    }
    return event;
  });
})();

After saving the settings and clicking on Update App, create a new record. Add new rows into the table, and fill it with data. After saving the record, the Number field of the table should automatically be numbered, starting with the number 1.