---
title: "Coding Forms"
url: "https://dev.4hse.com/guides/forms/coding-forms"
description: "Technical guide for the code of a 4HSE form: the onInit function, widget events, reading and changing fields, loading data from 4HSE."
---

# Coding Forms

This guide is for whoever writes the code of a form: the functions of the script, the available API, events, loading data. It describes the language, not the tools.

-   What forms, widgets and scripts are: [Form Concepts](/guides/forms/form-concepts/).
-   Where the script is written and how it is tested: [Simple Form Editor](/guides/forms/simple-form-editor/#script) and [Advanced Form Editor](/guides/forms/advanced-form-editor/#the-script).

## The script

[Section titled “The script”](#the-script)

The script is a set of **JavaScript functions**. The form attaches each one to a widget according to its **name**:

Function name

When it runs

`onInit`

once, when the form has been built

`<widgetId>On<Event>`

when the widget with that id triggers the event. `is_anonymousOnChange` runs when the value of `is_anonymous` changes

any other name

it is a **helper function**: it runs only when you call it, as `this.name()`

The event name is the one of the widget in camel case, after `On`: `EVENT_CHANGE` becomes `OnChange`, `EVENT_KEY_ENTER` becomes `OnKeyEnter`.

```
function updateAnonymity(value) {  const identity = this.getWidget('identity_container');  if (identity) {    identity.hidden = value === 'yes';  }}
function onInit(event) {  const anonymous = this.getWidget('is_anonymous');  this.updateAnonymity(anonymous && anonymous.data);}
function is_anonymousOnChange(event) {  this.updateAnonymity(event.params.data);}
```

Rules to keep in mind:

-   **Functions do not share variables.** To share code, write a helper function and call it with **`this.`** (`this.updateAnonymity(...)`): a call without `this.` does not find it. Inside a helper, `this` is the same as in the handlers.
-   **`onInit` runs after the handlers are attached**, so it can already change the widgets. It does not wait for requests: if it loads data, write the values when the answer arrives.
-   **The id of a widget decides the name of its handlers.** A widget with a hyphen in its id, such as `form-header`, cannot have handlers, because a function name cannot contain a hyphen: use letters, numbers and underscores, not starting with a number. The simple editor enforces this rule (see [Field identity](/guides/forms/simple-form-editor/#field-identity)); in the advanced editor the **Unique ID** is only checked for uniqueness, so check it yourself. A helper function must not be named like `<widgetId>On...`, or it is taken for a handler.
-   **An error does not stop the form.** A function with a syntax error is not attached, and a function that throws stops at that point. The message is written in the console of the browser, with the prefix `[hse-form]` and the name of the function: keep it open while you test.

## The API

[Section titled “The API”](#the-api)

Inside every function, `this` gives you:

In the code

What it holds

`this.getWidget(id)`

the widget with that id, or `undefined` if there is none

`this.root`

the form

`this.runtime.context`

the item the form was opened from, `{}` if there is none

`this.runtime.target`

the launch point the form was opened from, `null` if unknown

`this.name()`

a helper function of the script

`this.runtime.context` has the same keys as in reports:

Key

Content

`entity_id`

id of the item the form is opened from

`entity_type`

its type, uppercase (`ACTION_SESSION`, `EQUIPMENT`, `CERTIFICATE`…)

`office_id`, `office_country`

the office of the item (or the item itself, if it is an office)

`project_id`, `project_country`

the project

`unit_id`, `unit_country`

the unit or supplier, if any

A form opened from the file system does not start from an item, so the context may be empty: always check the values before you use them.

### Reading and changing a widget

[Section titled “Reading and changing a widget”](#reading-and-changing-a-widget)

A widget is an object whose properties you read and write directly. Changing a property updates the screen at once.

Property

Meaning

`data`

the value of the field

`hidden`

`true` hides the widget, and everything inside it if it is a row or a column

`disabled`

`true` makes the field read-only

`optionList`

the options of a dropdown or a checkbox: `[{ text, value, disabled }]`

`placeholder`

the text shown in an empty text field

The format of `data` depends on the widget:

Widget

`data`

text, text area

string

dropdown

the `value` of the selected option, `""` for none

checkbox group

array with the `value` of each checked option

date

`"yyyy-mm-dd"` (or `"yyyy-mm-dd hh:mm:ss"`), `""` for none, `"now"` for today

time

`"yyyy-mm-dd hh:ii"` in UTC, `""` for none, `"now"` for the current time

The blocks of 4HSE (the header, the attendance register…) receive what they need from the script as properties, for example `header.office_id = context.office_id`.

## Events

[Section titled “Events”](#events)

The handler receives an `event` argument. For a field, `event.params` holds:

Key

Content

`data`

the new value (for `OnChange`)

`widgetId`

the id of the widget

`name`

the name of the field

`alias`

the type of the widget

`target`

the widget itself

The events a widget supports depend on its type. The most common ones are:

Event

Function name

Triggered when

`EVENT_CHANGE`

`<id>OnChange`

the value changes (fields)

`EVENT_INPUT`

`<id>OnInput`

the user types in a text field

`EVENT_CLICK`

`<id>OnClick`

the user clicks

`EVENT_FOCUS`, `EVENT_BLUR`

`<id>OnFocus`, `<id>OnBlur`

the field gains or loses the focus

`EVENT_KEY_ENTER`

`<id>OnKeyEnter`

the user presses Enter in a text field

The form itself has `onInit`, and `<form id>OnChange`, triggered when any field of the form changes, with `event.params.data` being the data of the whole form.

If the id in the name of a handler does not exist in the form, the handler is not attached and `Unable to find descendant <id>` appears in the console.

## Loading data

[Section titled “Loading data”](#loading-data)

`fetch` works as in the rest of the app, with the session of the logged-in user: the form sees what the user can see. The forms of 4HSE use absolute paths to the [REST API v2](/guides/using-rest-api/):

-   one record: `fetch('/v2/<resource>/view?id=' + id)`
-   a list: `fetch('/v2/<resource>/index?filter[<field>]=' + value)`

The request is asynchronous: assign the values when the answer arrives. Check `response.ok`, because `fetch` does not fail on an HTTP error, and catch the errors so that a failed request leaves the form as it is. Fill only the empty fields: the user may have typed something before the answer arrives.

```
function onInit(event) {  const incidentId = this.runtime.context.entity_id;  if (!incidentId) {    return;  }
  const codeWidget = this.getWidget('report_code');  fetch('/v2/incident/view?id=' + encodeURIComponent(incidentId))    .then(function (response) {      return response.ok ? response.json() : null;    })    .then(function (incident) {      if (incident && codeWidget && !codeWidget.data) {        codeWidget.data = incident.code;      }    })    .catch(function () {});}
```

## Example: show a field only when needed

[Section titled “Example: show a field only when needed”](#example-show-a-field-only-when-needed)

The most common use of the script is to show or hide a group of fields according to an answer. The form has a dropdown `participation_feedback_occurred` and a container `participation_details_container` that starts hidden:

```
function updateParticipationDetails(value) {  const details = this.getWidget('participation_details_container');  if (details) {    details.hidden = value !== 'yes';  }}
function onInit(event) {  const gate = this.getWidget('participation_feedback_occurred');  this.updateParticipationDetails(gate && gate.data);}
function participation_feedback_occurredOnChange(event) {  this.updateParticipationDetails(event.params.data);}
```

Calling the same helper from `onInit` and from the handler keeps the form right both when it opens and when the answer changes. The ISO 45001 forms of the `print-templates` repository use this scheme.

## Guidelines

[Section titled “Guidelines”](#guidelines)

-   check that a widget exists before you use it (`if (widget)`): a wrong id gives `undefined`, not an error you can see;
-   write user-facing text in the widgets, not in the script;
-   keep the script short and use helper functions, not copies of the same code in several handlers;
-   set the initial visibility in `onInit` with the same helper as the handler, so the form is right even when it opens with values already filled in;
-   test the form with the console of the browser open: it is the only place where script errors are shown.

This site is protected by reCAPTCHA and the Google [Privacy Policy](https://policies.google.com/privacy) and [Terms of Service](https://policies.google.com/terms) apply.