Dynamic Forms

This is the official documentation of the @forestadmin/agent Node.js agent.

Business logic often requires your forms to adapt to their context. Forest Admin makes this possible through a powerful way to extend your form's logic.

To make an action form dynamic, simply use functions instead of a static value on the compatible properties.

Note that:

  • Both synchronous and asynchronous functions are supported

  • The functions take the same context object as the execute handler.

    • As such, they have access to the current values of the form.

    • And the records that the action will be applied to.

Form field properties

functions can be used for the following properties which are also available as static values:

PropertyDescription

isRequired

Make the field required.

isReadOnly

Make the field read-only.

defaultValue

Set the default value of the field.

description

Set the text displayed below the label

In addition, depending on the field type, you can also use functions for the following properties:

PropertyDescription

enumValues

Change the list of possible values of the field when type == 'Enum'.

collectionName

Change the target collection of the field when type: 'Collection'.

Some widgets also support dynamic configuration:

PropertyWidgetDescription

options

Change the list of possible values of the field.

min

Define the min value that can be entered by the user.

max

Define the max value that can be entered by the user.

step

Define the step value of the input.

And finally, those two extra properties are available and can only be used as functions:

PropertyDescription

if

Only display the field if the function returns true.

value

Set the current value of the field.

Examples

Example 1: Dynamic fields based on form values

In this example we make a field required only if the user enters a value greater than 1000 in another field.

agent.customizeCollection('customer', collection => {
  collection.addAction('Charge credit card', {
    scope: 'Single',
    form: [
      {
        label: 'amount',
        type: 'Number',
        description: 'The amount (USD) to charge the credit card. Example: 42.50',
        isRequired: true,
      },
      {
        label: 'description',
        type: 'String',
        description: 'Explain why you want to charge the customer manually',

        /**
         * The field will only be required if the function returns true.
         */
        isRequired: context => context.formValues['amount'] > 1000,
      },
    ],
    execute: async (context, resultBuilder) => {
      // ...
    },
  });
});

Example 2: Conditional field display based on record data

Unlike the previous example, this one will only display the field if the record has a specific value.

It is still a dynamic field, but this time, the condition does not depend on the form values but on the record data.

agent.customizeCollection('product', collection => {
  collection.addAction('Leave a review', {
    scope: 'Single',
    form: [
      { label: 'Rating', type: 'Enum', enumValues: ['1', '2', '3', '4', '5'] },

      // Only display this field if the rating is 4 or 5
      {
        label: 'Put a comment',
        type: 'String',
        if: context => Number(context.formValues.Rating) >= 4,
      },
    ],
    execute: async context => {
      /* ... perform work here ... */
    },
  });
});

Example 3: Conditional enum values based on both record data and form values

You can mix and match the previous examples to create complex forms.

In this example, the form will display a different set of enum values depending on both the record data and the value of the form field.

The first field displays different denominations that can be used to address the customer, depending on the full name and gender of the customer.

The second field displays different levels of loudness depending on if the customer is Morgan Freeman, as to ensure that we never speak Very Loudly at him, for the sake of politeness.

agent.customizeCollection('customer', collection => {
  collection.addAction('Tell me a greeting', {
    scope: 'Single',
    form: [
      {
        label: 'How should we refer to you?',
        type: 'Enum',
        enumValues: async context => {
          // Enum values are computed based on the record data
          // Use an async function to fetch the record data
          const user = await context.getRecord(['firstName', 'lastName', 'gender']);
          const base = [user.firstName, `${user.firstName} ${user.lastName}`];

          if (gender === 'Female') {
            return [...base, `Mrs. ${user.lastName}`, `Miss ${user.lastName}`];
          } else {
            return [...base, `Mr. ${user.lastName}`];
          }
        },
      },
      {
        label: 'How loud should we say it?',
        type: 'Enum',
        enumValues: context => {
          // Enum values are computed based on another form field value
          // (no need to use an async function, but doing so would not be a problem)
          const denomination = context.formValues['How should we refer to you?'];

          return denomination === 'Morgan Freeman'
            ? ['Whispering', 'Softly', 'Loudly']
            : ['Softly', 'Loudly', 'Very Loudly'];
        },
      },
    ],
    execute: async (context, resultBuilder) => {
      const denomination = context.formValues['How should we refer to you?'];
      const loudness = context.formValues['How loud should we say it?'];

      let text = `Hello ${denomination}`;
      if (loudness === 'Whispering') {
        text = text.toLowerCase();
      } else if (loudness === 'Loudly') {
        text = text.toUpperCase();
      } else if (loudness === 'Very Loudly') {
        text = text.toUpperCase() + '!!!';
      }

      return resultBuilder.success(text);
    },
  });
});

Example 4: Using hasFieldChanged to reset value

In this example we reset a field based on change on another one.

agent.customizeCollection('customer', collection => {
  collection.addAction('Create banking identity', {
    scope: 'Single',
    form: [
      {
        label: 'Bank Name',
        type: 'Enum',
        enumValues: ['CE', 'BP'],
        isRequired: true,
      },
      {
        label: 'BIC',
        type: 'String',
        value: context => {
          if (context.hasFieldChanged('Bank Name')) {
            return context.formValues['Bank Name'] === 'CE'
              ? 'CEPAFRPPXXX'
              : 'CCBPFRPPXXX';
          }
        },
      },
    ],
    execute: async (context, resultBuilder) => {
      // ...
    },
  });
});

Example 5: Setting up default value based on the record

In this example we setup a the default value of a field based on the current record.

agent.customizeCollection('order', collection => {
  collection.addAction('Change order price', {
    scope: 'Single',
    form: [
      {
        label: 'New Price',
        type: 'Number',
        defaultValue: async context => {
          return (await context.getRecord(['amount'])).amount;
        },
      },
    ],
    execute: async (context, resultBuilder) => {
      // ...
    },
  });
});

Example 6: Block field edition

In this example we make a field read only based on a field from the current record.

agent.customizeCollection('order', collection => {
  collection.addAction('Change order price', {
    scope: 'Single',
    form: [
      {
        label: 'New Price',
        type: 'Number',
        defaultValue: async context => {
          return (await context.getRecord(['amount'])).amount;
        },
        isReadOnly: async context => {
          return (await context.getRecord(['status'])).status === 'paid';
        },
      },
    ],
    execute: async (context, resultBuilder) => {
      // ...
    },
  });
});

Last updated