# Form (fw-form)

Dynamic Form - Render dynamic form based on the schema passed as a prop.
Static Form - Render form based on the children passed as slots.

# Demo Dynamic Form

Pass formSchema to render Dynamic Form. You can also pass initialValues to the form.

Submit Reset
Show Code

# FormSchema with field type 'DATE'

Datepicker by default will be highlighted and alert icon will be displayed when invalid value is entered in the date input field. To switch it off, set the property 'showErrorOnInvalidDate' to false.

showErrorOnInvalidDate - Setting the prop to false will not highlight the datepicker in error state when user enters invalid input and will not display the error msg in the tooltip. However, the invalid value will not be submitted to backend on clicking 'Update' button.

Example form schema,

var formSchema = {
    name: 'Test Form',
    fields: [
      {
        id: 'f319f86f-1b6a-49cb-b4b6-cf487be94595',
        name: 'date_of_birth',
        label: 'Date Of Birth',
        type: 'DATE',
        position: 11,
        required: true,
        Placeholder: 'Enter…',
        hint: 'Please enter your date of birth',
        choices: [],
        showErrorOnInvalidDate: false,
      }
    ],
  };

# FormSchema with field type 'DATE' to occupy full width of the container

Datepicker by default will not occupy full width of the container. To make the datepicker occupy full width, set 'fullWidth' prop as true in the form schema.

Example form schema,

var formSchema = {
    name: 'Test Form',
    fields: [
      {
        id: 'gt19f86f-1b6a-49cb-b4b6-cf487be97899',
        name: 'date_of_birth',
        label: 'Date Of Birth',
        type: 'DATE',
        position: 1,
        required: true,
        Placeholder: 'Enter…',
        hint: 'Please enter your date of birth',
        choices: [],
        fullWidth: true,
      }
    ],
  };

# form schema

form schema should follow the below structure:

name: '', // Name of the form.
fields: [ // Each item in this array corresponds to a crayons input component.
  {
    id: '2978f820-704b-46c7-9f88-110e14e34a8c', // ID of the input control
    name: 'first_name', // Will be used while serializing form.
    label: 'First Name', // Label to display.
    type: '', // Type of the crayons input component. Possible values are TEXT/NUMBER/DECIMAL/DROPDOWN/MULTI_SELECT/RADIO/CHECKBOX/DATE/PARAGRAPH/EMAIL/TIME/DATE_TIME/FILES
    position: 3, // Order of the component in the form.
    required: true, // Required while submitting the form.
    editable: false // setting this to false, will disable the field.
    placeholder: 'Enter…', // placeholder for the input
    hint: 'Please provide a text of at max 100 characters', // Hint text to be displayed below.
    choices: [], // List of options for DROPDOWN/MULTI_SELECT types. Each option should be of below structure:
    {
    id: 1, // ID for the option.
    text: '', // Text for the option.
    value: '', // Value for the option.
    }
  }
]
}

# Disable form fields

In a Dynamic form, to disable any form field set editable to false in the form schema. You will not be able to set a value dynamically to the disabled form field. Instead set the value via initialValues. In a Static form set disabled attribute on the fw-form-control to disable the form field.

# Usage Dynamic Form

# Text and Value indicators for select (DROPDOWN/MULTI_SELECT) component choices

The choices for select component(dropdown/multi_select) can follow any of the below formats.

  1. Using field_options object. Pass the key name that needs to be displayed as the dropdown option's text using, option_label_path and the key name that needs to to be processed in the backend using, option_value_path.
{
  id: '420oib8f-25cf-47ce-89c6-5410fe3d4315',
  name: 'languages_known',
  label: 'Languages Known',
  type: 'MULTI_SELECT',
  position: 1,
  required: true,
  placeholder: 'Choose',
  hint: 'Select one or more values',
  field_options: {
    option_label_path: 'value', // This denotes 'value' in the choices object needs to be displayed as the dropdown option text,i.e English & Hindi
    option_value_path: 'id',  // This denotes 'id' in the choices object needs to be used as the dropdown option's value for backend
  },
  choices: [
    {
      id: 1,  // this will be passed to the backend if `English` has been selected in the dropdown options.
      value: 'English',  // This will be displayed in the dropdown options list.
      position: 1,
      dependent_ids: {},
    },
    {
      id: 2,
      value: 'Hindi',
      position: 2,
      dependent_ids: {},
    },
  ],
}

# Usage with field_options

Submit Reset
Show Code
  1. Using text and value as key names in choices
{
  id: '127yub8f-25cf-47ce-89c6-67yufe3d4315',
  name: 'languages_known',
  label: 'Languages Known',
  type: 'MULTI_SELECT',
  position: 1,
  required: true,
  placeholder: 'Choose',
  hint: 'Select one or more values',
  choices: [
    {
      value: 1,  // this will be passed to the backend if `English` has been selected in the dropdown options.
      text: 'English',  // This will be displayed in the dropdown options list.
      position: 1,
      dependent_ids: {},
    },
    {
      id: 2,
      value: 'Hindi',
      position: 2,
      dependent_ids: {},
    },
  ],
}

# Usage with text and value as keys in choices

Submit Reset
Show Code

# Demo Static Form

You can pass initialValues to the form. Wrap all the form controls with form-control under fw-form.

For Crayons controls just pass the type, name, placeholder,required, label properties to fw-form-control.

For custom input controls, pass the custom input as slot to fw-form-control. You can pass the type, name, required, label properties to fw-form-control. For setting its value in the form, use the method like handleCustomInput shown in the below example.

You can use fieldProps to pass any crayons input control related properties. Set fieldProps: { maxlength: 5 } to fw-form-control

Submit Reset
Show Code

# Usage Static Form

# Demo - Form inside an accordion

Form can be created inside an accordion by passing the form to accordion body.

Title
Submit Reset
Show Code

# Usage - Form inside an accordion

# FORMSERV - mapperType

Set FORMSERV to mapperType prop to use FORMSERV schema instead of default LEGO schema.

Submit Reset
Show Code

# Filter Display of Form Fields

Invoke setFieldSearchText method on the form passing a text that filters the display of the form fields matching the field's label.

Show Code

# Dynamically Set Field Choices

Invoke setFieldChoices method on the form passing the name of the field and choices array to update the choices in the DROPDOWN/MULTI_SELECT form's field-control.

Submit Reset Update Choices Of Order Status
Show Code

# Set Required Status on the Form Fields

Use setFieldsRequiredStatus method to set required status on the form fields dynamically.

param: requiredStatusObj - Object with key as form field name and value denoting if the field should be marked as required or not

Example: setFieldsRequiredStatus({ first_name: true, last_name: true })

# Set Value on the Form Fields Dynamically

Use setFieldsValue method to set values on the form fields dynamically.

param: valuesObj - Object with key as form field name and value as the updated value for the field.

shouldValidate - should this form be validated with the updated values. Default to true

Example: setFieldsValue({ first_name: "new name", last_name: "new last name" }, true)

# Validations

Validation can be done using Yup (opens new window) based validationSchema or validate function prop.

# Validations Usage

You can use validationSchema prop to do Yup based validation. Please use 0.32 version of Yup.

const validationSchema = Yup.object().shape({
  first_name: Yup.string()
    .required('First name is required')
    .min(5, 'min 5 char')
    .nullable(),
});
// get reference to fw-form and set validationSchema prop.

You can also use validate async function prop to do any custom validation.

const validate = async (values: any) => {
  // do custom validation and return error or {}
  return {
    // last_name: "last name is errored",
  };
};
// get reference to fw-form and set validate function prop.

Both validationSchema and validate prop can be used together.

# Validation using Yup schema

Install Yup via CDN as below:

import * as Yup from 'https://cdn.skypack.dev/yup@0.32';
window.Yup = Yup;
Submit Reset
Show Code

# Interfaces

# FormValues

type FormValues = {
  [field: string]: any,
};

# FormSubmit

type FormSubmit = {
  values: FormValues,
  errors: FormErrors<FormValues>,
  isValid: boolean,
};

# FormErrors

type FormErrors = {
  [K in keyof FormValues]?: string;
};

# FormRequired

type FormRequired = {
  [K in keyof FormValues]?: boolean;
};

# Form Value Change Event

fwFormValueChanged event gets emitted whenever there is a change in the value of any of the form field.

var form = document.querySelector('fw-form');
form.addEventListener('fwFormValueChanged', (e) => {
  console.log('field', e.detail.field);
  console.log('value', e.detail.value);
});

# Form Values Change Event

fwFormValuesChanged event gets emitted whenever there is a change in the value of any of the form field. Returns the current form state with the value of all the form fields.

var form = document.querySelector('fw-form');
form.addEventListener('fwFormValuesChanged', (e) => {
  console.log('current form value', e.detail.value);
});

# Properties

Property Attribute Description Type Default
customTypeMapper custom-type-mapper A custom type mapper object that maps the type of your fields in the schema to the Internal Field Types. Internal Field Types are TEXT, DROPDOWN, EMAIL etc. In the example below, 1 is the type of a field in your schema that needs to correspond to TEXT type. Please pass include the mapper for all the field types that you want to support. Example typeMapper object : { 'CUSTOM_TEXT': { type: 'TEXT' }, 'SELECT': { type: 'DROPDOWN' }, 'TEL': { type: 'PHONE_NUMBER' }, 'CHECKBOX': { type: 'CHECKBOX' }, 'TEXTAREA': { type: 'PARAGRAPH' }, 'DATETIME': { type: 'DATE_TIME' }, 'INTEGER': { type: 'NUMBER' }, } any {}
formId form-id Id to uniquely identify the Form. If not set, a random Id will be generated. any uuidv4()
formSchema form-schema Schema to render Dynamic Form. Contains an array of fields pointing to each form control. Please see the usage reference for examples. any {}
initialValues initial-values Initial field values of the form. It is an object with keys pointing to field name any {}
mapperType mapper-type Mapper Type - LEGO | FORMSERV | CUSTOM. Defaults to LEGO. "CUSTOM" \| "FORMSERV" \| "LEGO" LEGO
validate validate Validate the form's values with an async function. Should return a Promise which resolves to an errors object. The keys in the errors object must match with the field names. any undefined
validateOnBlur validate-on-blur Tells Form to validate the form on each input's onBlur event boolean true
validateOnInput validate-on-input Tells Form to validate the form on each input's onInput event boolean true
validationSchema validation-schema YUP based validation schema for handling validation any {}
wait wait The number of milliseconds to delay before doing validation on Input number 200

# Events

Event Description Type
fwFormValueChanged fwFormValueChanged - event that gets emitted when value in a form field changes. CustomEvent<any>
fwFormValuesChanged fwFormValuesChanged - event that gets emitted when values change. CustomEvent<any>

# Methods

# doReset(event?: any) => Promise<void>

# Returns

Type: Promise<void>

# doSubmit(event?: any) => Promise<FormSubmit>

# Returns

Type: Promise<FormSubmit>

# getValues() => Promise<{ values: FormValues; serializedValues: FormValues; }>

getValues

# Returns

Type: Promise<{ values: FormValues; serializedValues: FormValues; }>

An Object containing values and serializedValues. serializedValues are those that contains the transformed values based on field type.

  1. For Number and Decimal: returns floating point number of value or undefined.
  2. For Date: returns value as ${year}-${month}-${date} or undefined.
  3. For Relationship : returns an array of values or value.

# setDisabledFields(disabledFields?: any) => Promise<void>

Method to set disabled fields on the form dynamically.

Note: You must always pass all the fields that you want to disable

param: disabledFields - key value pair of [fieldName]: true | false example: setDisabledFields({ first_name: true, last_name: false })

# Returns

Type: Promise<void>

# setFieldChoices(field: string, choices: Array<any>, fieldOptions?: any) => Promise<void>

setFieldChoices Method to set field choices for a DROPDOWN/MULTI_SELECT/RADIO fields in formschema. choices must be in the form of array with the below format: [{ id: 1, value: 'open', position: 1, dependent_ids: {}, }]. fieldOptions is an optional parameter, must be an object with keys being option_label_path and option_value_path. option_label_path refers to the key used for displaying the text. option_value_path refers to the key which corresponds to the value of item.

# Returns

Type: Promise<void>

# setFieldErrors(errorObj: FormErrors<FormValues>) => Promise<void>

Method to set errors on the form fields.

If you use setErrors, your errors will be wiped out by next validate or validationSchema call which can be triggered by the user typing (a change event) or blurring an input (a blur event). Note: this assumed you have not manually set validateOnInput and validateOnBlur props to false (they are true by default).

param: errorObj - key value pair of [fieldName]: ErrorMessage example: { first_name: 'firstname is required' }

# Returns

Type: Promise<void>

# setFieldSearchText(text: string) => Promise<void>

Method to filter the display of fields in the form based on the passed text.

# Returns

Type: Promise<void>

# setFieldValue(field: string, value: any, shouldValidate?: boolean) => Promise<void>

Method to set value on the form field.

param: field - name of the form field param: value - value of the form field param: shouldValidate - should this form field be validated with the updated value. Default to true.

# Returns

Type: Promise<void>

# setFieldsRequiredStatus(requiredStatusObj: FormRequired<FormValues>) => Promise<void>

Method to set required status on form fields

param: requiredStatusObj - Object with key as form field name and value denoting if the field should be marked as required or not example: { first_name: true, last_name: false }

# Returns

Type: Promise<void>

# setFieldsValue(valuesObj: FormValues, shouldValidate?: boolean) => Promise<void>

Method to set values on the form fields.

param: valuesObj - Object with key as form field name and value as the updated value for the field example: { first_name: "new name", last_name: "new last name" } param: shouldValidate - should this form be validated with the updated values. Default to true.

# Returns

Type: Promise<void>

# setHiddenFields(hiddenFields?: any) => Promise<void>

Method to set hidden fields on the form dynamically.

Note: You must always pass all the fields that you want to hide. Also, note that the validation for hidden fields will be skipped.

param: hiddenFields - key value pair of [fieldName]: true | false example: setHiddenFields({ first_name: true, last_name: false })

# Returns

Type: Promise<void>

# Dependencies

# Depends on

# Graph

graph TD;
  fw-form --> fw-form-control
  fw-form-control --> fw-input
  fw-form-control --> fw-textarea
  fw-form-control --> fw-datepicker
  fw-form-control --> fw-checkbox
  fw-form-control --> fw-radio-group
  fw-form-control --> fw-radio
  fw-form-control --> fw-select
  fw-form-control --> fw-timepicker
  fw-form-control --> fw-file-uploader-2
  fw-input --> fw-icon
  fw-datepicker --> fw-tooltip
  fw-datepicker --> fw-icon
  fw-datepicker --> fw-button
  fw-datepicker --> fw-input
  fw-datepicker --> fw-timepicker
  fw-datepicker --> fw-popover
  fw-datepicker --> fw-select
  fw-tooltip --> fw-popover
  fw-button --> fw-spinner
  fw-button --> fw-icon
  fw-timepicker --> fw-select
  fw-timepicker --> fw-select-option
  fw-select --> fw-tag
  fw-select --> fw-popover
  fw-select --> fw-button
  fw-select --> fw-spinner
  fw-select --> fw-icon
  fw-select --> fw-list-options
  fw-tag --> fw-tooltip
  fw-tag --> fw-avatar
  fw-tag --> fw-icon
  fw-list-options --> fw-select-option
  fw-list-options --> fw-input
  fw-select-option --> fw-icon
  fw-select-option --> fw-checkbox
  fw-select-option --> fw-avatar
  fw-checkbox --> fw-icon
  fw-file-uploader-2 --> fw-file-2
  fw-file-uploader-2 --> fw-inline-message
  fw-file-2 --> fw-icon
  fw-file-2 --> fw-tooltip
  fw-file-2 --> fw-spinner
  fw-inline-message --> fw-icon
  style fw-form fill:#f9f,stroke:#333,stroke-width:4px

Built with ❤ at Freshworks