Calculate field value on save

Displaying a preferred unit to end users, but always save a standardised unit

Try it out!

Scenario

Forms will often have number fields for inputting measurements, which could be in different units such as ounces and kilograms, centimetres and inches, or even different currencies.

This guide will demonstrate how to allow an End User to select a unit of measurement, that will automatically convert the value, but making sure that any row saved will use a standardised unit of meters.

Challenge:
★★★☆☆

Steps

  1. Add component: Form, and set the Schema to your table with the 'Distance' number column
  2. Add component: Field Group
  3. In the Settings Panel, click Update form fields
  1. Add component: Options Picker

  2. In the Settings Panel, manually enter a Field name of 'UnitPicker'

  3. Provide a Label: 'Unit'

  4. Set the Default Value to 1

  5. Uncheck Alphabetical

  6. Set Options source to 'Custom'

  7. Click Define Options:

    LabelValue
    Feet0.305
    Yards0.914
    Meters1
  1. Click the button beside On change

  2. Add Action: Update Field Value

    1. Select the Form
    2. Set Type to 'Set value'
    3. Select the Distance form field
    4. Click the lightning bolt and select the JavaScript tab. Add the following:
    const previousUnit = $("Form.Fields.UnitPicker");
    const newUnit = $("Field Value");
    const previousDistance = $("Form.Fields.Distance");
    
    return (previousDistance * (previousUnit / newUnit)).toFixed(4);
    

📘

Previous and new values on change

It's worth bringing attention to the use of the options picker bindings.

$("Form.Fields.UnitPicker") will get the value of the field before the change occurs.

$("Field Value") is the new value that will update the field when the on change finishes.

  1. Click the button beside Validation
  2. Add Rule: Required and type in an error message to display
  3. Be sure to Save
  1. Add component: Button
  2. In the Settings Panel, click the button beside On click
  3. Add Action: Validate Form and select the form
  4. Add Action: Save Row
  5. Select the form as the Datasource, and the destination Table
  6. Add Column: Select the 'Distance column' and provide the following binding: {{ multiply Form.Fields.Distance Form.Fields.UnitPicker }}
  7. Save


App export

Downloads may take a few seconds.