Dynamic Forms

This is the official documentation of the agent_ruby Ruby 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:

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

Property
Description

enum_values

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

collection_name

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

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

Property
Description

if_condition

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.

include ForestAdminDatasourceCustomizer::Decorators::Action
include ForestAdminDatasourceCustomizer::Decorators::Action::Types
include ForestAdminDatasourceCustomizer::Decorators::Action::Context

@create_agent.customize_collection('customer') do |collection|
  collection.add_action(
    'Charge credit card',
    BaseAction.new(
      scope: ActionScope::SINGLE,
      form: [
        {
          label: 'amount',
          type: FieldType::NUMBER,
          description: 'The amount (USD) to charge the credit card. Example: 42.50',
          is_required: true,
        },
        {
          label: 'description',
          type: FieldType::STRING,
          description: 'Explain why you want to charge the customer manually',

          # The field will only be required if the function returns true.
          is_required: ->(context) { context.get_form_value['amount'].to_i > 1000 },
        },
      ]
    ) do |context|
      # ...
    end
  )
end

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.

include ForestAdminDatasourceCustomizer::Decorators::Action
include ForestAdminDatasourceCustomizer::Decorators::Action::Types
include ForestAdminDatasourceCustomizer::Decorators::Action::Context

@create_agent.customize_collection('product') do |collection|
  collection.add_action(
    'Leave a review',
    BaseAction.new(
      scope: ActionScope::SINGLE,
      form: [
        {
          label: 'Rating',
          type: FieldType::ENUM,
          enum_values: ['1', '2', '3', '4', '5'],
        },
        {
          label: 'Put a comment',
          type: FieldType::STRING,
          # Only display this field the data does not have comment already
          if_condition = proc do |context|
            record = context.get_record(['comment'])
            !record[:comment].nil?
          end,
        },
      ]
    ) do |context|
      # ... perform work here ...
    end
  )
end

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.

include ForestAdminDatasourceCustomizer::Decorators::Action
include ForestAdminDatasourceCustomizer::Decorators::Action::Types
include ForestAdminDatasourceCustomizer::Decorators::Action::Context

@create_agent.customize_collection('customer') do |collection|
  collection.add_action(
    'Tell me a greeting',
    BaseAction.new(
      scope: ActionScope::SINGLE,
      form: [
        {
          label: 'How should we refer to you?',
          type: FieldType::ENUM,
          enum_values: ->(context) {
            # Enum values are computed based on the record data
            # Because we need to fetch the record data, we need to use an async function
            user = context.get_record(%w[firstName lastName gender])
            base = [user['firstName'], "#{user['firstName']} #{user['lastName']}"]

            if gender == 'Female'
              base << "Mrs. #{user['lastName']}"
              base << "Miss. #{user['lastName']}"
            else
              base << "Mr. #{user['lastName']}"
            end

            base
          }
        },
        {
          label: 'How loud should we say it?',
          type: FieldType::ENUM,
          enum_values: ->(context) {
            # Enum values are computed based on another form field value
            # (no need to use an async function here, but doing so would not be a problem)
            denomination = context.form_values['How should we refer to you?']

            if denomination == 'Morgan Freeman'
              ['Whispering', 'Softly', 'Loudly']
            else
              ['Softly', 'Loudly', 'Very Loudly']
            end
          }
        }
      ]
    ) do |context, result_builder|
        denomination = context.form_values['How should we refer to you?']
        loudness = context.form_values['How loud should we say it?']

        text = "Hello #{denomination}"
        if loudness == 'Whispering'
            text = text.downcase
        elsif loudness == 'Loudly'
            text = text.upcase
        elsif loudness == 'Very Loudly'
            text = "#{text.upcase}!!!"
        end

        result_builder.success(text)
    end
  )
end

Example 4: Using hasFieldChanged to reset value

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

include ForestAdminDatasourceCustomizer::Decorators::Action
include ForestAdminDatasourceCustomizer::Decorators::Action::Types
include ForestAdminDatasourceCustomizer::Decorators::Action::Context

@create_agent.customize_collection('customer') do |collection|
  collection.add_action(
    'Create banking identity',
    BaseAction.new(
      scope: ActionScope::SINGLE,
      form: [
        {
          type: FieldType::ENUM,
          label: 'Bank Name',
          is_required: true,
          enum_values: %w[CE BP]
        },
        {
          type: FieldType::STRING,
          label: 'BIC',
          if_condition: ->(context) { context.has_field_changed('Bank Name') },
          value: ->(context) { context.form_values['Bank Name'] == 'CE' ? 'CEPAFRPPXXX' : 'CCBPFRPPXXX' }
        }
      ]
    ) do |context, result_builder|
      #...
    end
  )
end

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.

include ForestAdminDatasourceCustomizer::Decorators::Action
include ForestAdminDatasourceCustomizer::Decorators::Action::Types
include ForestAdminDatasourceCustomizer::Decorators::Action::Context

@create_agent.customize_collection('customer') do |collection|
  collection.add_action(
    'Change order price',
    BaseAction.new(
      scope: ActionScope::SINGLE,
      form: [
        {
          type: FieldType::NUMBER,
          label: 'New Price',
          default_value: ->(context) { context.get_record(['amount'])['amount'] }
        }
      ]
    ) do |context, result_builder|
      #...
    end
  )
end

Example 6: Block field edition

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

include ForestAdminDatasourceCustomizer::Decorators::Action
include ForestAdminDatasourceCustomizer::Decorators::Action::Types
include ForestAdminDatasourceCustomizer::Decorators::Action::Context

@create_agent.customize_collection('customer') do |collection|
  collection.add_action(
    'Change order price',
    BaseAction.new(
      scope: ActionScope::SINGLE,
      form: [
        {
          type: FieldType::NUMBER,
          label: 'New Price',
          default_value: ->(context) { context.get_record(['amount'])['amount'] },
          is_read_only: ->(context) { context.get_record(['status'])['status'] == 'paid' }
        }
      ]
    ) do |context, result_builder|
      #...
    end
  )
end

Last updated