Tutorial: Default column with simple js script

Hi @ll.

Today I like to share a way to set a default value (check box) by one click. It can be achieved with a simple js script, some columns and a view.

  1. Create 3 new columns with names: Default (type: check box), Set default (type: button) and Changed (type: Last modified time). The button-column will be modified later, just create one without any actions.
    grafik

    You have to add one action to save the button column settings:
    grafik

  2. Create a new view with the name “Ordered by newest” and set a sorting by the column “Changed” > Down. This view should never be changed under any circumstances. The script will fail if you do so!

  3. Create a new javascript and paste the following code into it. If you decide to use a different column name for “Default” and a different view name for “Ordered by newest” you have to modify the vars.

// vars
const viewName = 'Ordered by newest';
const defaultColumnName = 'Default';

// code - don't change careless!
const currentRow = base.context.currentRow;
const table = base.getActiveTable();
const view = base.getViewByName(table, viewName);
const rows = base.getRows(table, view);
const selectedRows = [], updatedRows = [];

let pos = 1;
rows.forEach((row) => {
  if (pos > 1 && row[defaultColumnName])
  {
    selectedRows.push(row);
    updatedRows.push({Default: false});
  }
  pos++;
});

base.modifyRows(table, selectedRows, updatedRows);
  1. Now edit the column “Set default” and add the second action “Run script”. Select the script you added in step 3.

If you now push the button “Set” the checkbox in the “Default” column will be checked and the other checkboxes will be unchecked even if there is more than one. The script will take care of it.

This should be all to have a default column for that table. You can create the three columns in every other table of the base and use the same script there too.

Enjoy!

2 Likes