@bolttech/form-engine
v3.0.3
Published
A react adapter for bolttech form engine
Maintainers
Keywords
Readme
Form Engine React Adapter
This is an adapter to be used with the bolttech form engine. Compatible with Next.js 13 and 14 and react 18.
- 4.1 Submit Form
- 6.1 formatters
- 6.2 masks
- 6.3 nameToSubmit
- 6.4 props
- 6.5 validations
- 6.6 api
- 6.7 resetValues
- 6.8 visibilityConditions
- 6.9 resetPropertyValues
- 6.10 visibility
- 6.11 persistValue
- 8.1 useForm
- 8.2 useFormGroup
Sample
const mappers: TMapper<ElementType>[] = [
{
componentName: 'input',
component: Input,
events: {
getValue: 'onChange',
setValue: 'value',
setErrorMessage: 'errorMessage',
onBlur: 'onBlur',
onFocus: 'onFocus',
},
valueChangeEvent: (event: unknown) => {
return (event as ChangeEvent<HTMLInputElement>).target.value;
},
},
{
componentName: 'container',
asyncComponent: lazy(() =>
import('Components/Container').then((module) => ({
default: module.Container,
}))
),
},
];
const schema = {
index: 'form1',
components: [
{
component: 'container',
name: 'container1',
children: [
{
component: 'input',
name: 'input1',
props: {
label: 'input1 label',
},
},
],
},
],
};
const ComponentProvider = ({ children }: PropsWithChildren) => {
return <FormGroupContextProvider mappers={mappers}>{children}</FormGroupContextProvider>;
};
const ComponentWithForm = ({ schema }: { schema: IFormSchema }) => {
const { printFormGroupInstance } = useFormGroupContext();
const handleData = (data: TFormData<unknown>) => {
console.log(data);
};
return (
<>
<button onClick={printFormGroupInstance}>print form instance</button>
<Form index={schema.index} schema={schema} onData={handleData} />
</>
);
};
const Sample = () => {
return (
<ComponentProvider>
<ComponentWithForm schema={schema} />
</ComponentProvider>
);
};Mappers
Mappers are the configuration that needs to be provided in order to use components onto schemas or a special component that render form fields
The mapper configuration goes as it follows:
| Prop | Type | Description | | ---------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------ | | componentName | string | name to be used onto schema to identify the component to be rendered on a field | | events | TComponentPropsMapping | events mapping that will reference the component prop with the respective form-engine prop that will handle it's content | | valueChangeEvent | TValueChangeEvent | component handle function to define how the value is extracted from the 'onChange' event of the component | | component | T | component type that describes a normal imported component to be used on the field rendering | | asynccomponent | T | component type that describes an async (lazy) imported component to be used on the field rendering |
events are optional and will reference component props that will provide it's dynamic behaviour:
| Prop | Type | Description | | --------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | getValue | string | component property that will contain the value | | setValue | string | component property that handles onChange events triggered by the component | | onBlur | string | component property that handles onBlur events triggered by the component | | onClick | string | component property that handles onClick events triggered by the component | | onSubmit | string | component property that handles form submission event triggered by the component (a way to submit a form using AsFormFieldBuilder, if used with AsFormField and Form will trigger submission twice) | | onFocus | string | component property that handles onFocus events triggered by the component | | onKeyUp | string | component property that handles onKeyUp events triggered by the component | | onKeyDown | string | component property that handles onKeyDown events triggered by the component | | setErrorMessage | string | component property that receives the errors of the field as string | | setErrorState | string | component property that receives the error status of the field as boolean (not implemented) |
component and asynccomponent
You can choose the way your component is imported, you can directly import the component that will be bundled on your project when built,
or with React's lazy or any other method to be used with React's Suspense to load it asyncronously and allow code splitting.
Example:
import { Input } from '@bolttech/atoms-input';
const mappers = [
{
component: Input,
name: 'inputcomponent',
},
{
component: lazy(() =>
import('@bolttech/atoms-input').then((module) => ({
default: module.Input,
}))
),
name: 'inputasynccomponent',
},
];from v2 to v3
Previously, mappers was two lists: mappings and propsMappings, now it's a single list, a simple example how to refactor a mapper:
//v2
const mappings = {
input: { component: Input },
};
const propsMappings = {
input: {
getValue: 'onChangeCallback',
setValue: 'data',
setErrorMessage: 'errorMessageArray',
setErrorState: 'isErrored',
onBlur: 'onBlurCallback',
onFocus: 'onFocusCallback',
onKeyUp: 'onKeyUpCallback',
onKeyDown: 'onKeyDownCallback',
},
};
//v3
const mappers = [
{
component: Input,
componentName: 'input',
events: {
getValue: 'onChangeCallback',
setValue: 'data',
setErrorMessage: 'errorMessageArray',
setErrorState: 'isErrored',
onBlur: 'onBlurCallback',
onFocus: 'onFocusCallback',
onKeyUp: 'onKeyUpCallback',
onKeyDown: 'onKeyDownCallback',
},
valueChangeEvent: (event: unknown) => {
return (event as SyntheticEvent<HTMLInputElement>).currentTarget.value;
},
},
];for bolltech components, there are valueChangeEvent default functions provided by form-engine:
- defaultChangeEvent -
atoms/input|atoms/textarea - checkedChangeEvent -
atoms/checkbox - valueChangeEvent -
atoms/input|atoms/textarea - datepickerChangeEvent -
molecules/datepicker - dropdownChangeEvent -
molecules/dropdown
Example:
import { Input } from '@bolttech/atoms-input';
import { defaultChangeEvent } from '@bolttech/form-engine';
const mapper = [
{
component: Input,
componentName: 'input',
events: {
getValue: 'onChange',
setValue: 'value',
setErrorMessage: 'errorMessage',
onBlur: 'onBlur',
onFocus: 'onFocus',
onKeyUp: 'onKeyUp',
onKeyDown: 'onKeyUpCapture',
},
valueChangeEvent: defaultChangeEvent,
},
];Form Group Context
FormGroupContextProvider
Provider of the context surrounding the child components, providing the state and functions to manage the group of forms.
Props
| Prop | Type | Description |
| --------- | ---------------------- | ------------------------------------------------------------------------------------------------------ |
| mappers | TMapper[] | Array of mappers for form element types. Allow you to map your own components to be used with the form |
| debugMode | boolean | Optional flag to enable debug mode (default: false). |
| config | TSchemaFormConfig | Optional configuration object to set api and events debounce time |
Implementation
- Creates a reference to the form group instance.
- Defines functions for adding, getting, and removing forms from the group.
- Defines a function to print the form group instance.
- Defines a function to submit multiple forms via the index.
- Defines the value of the context with the created functions and states.
- Returns the context provider involving the child components.
Calling provider
import React from 'react';
import { FormGroupContextProvider } from '@bolttech/form-engine'; // Import the previously created provider
import { mappers } from 'project/mappers'; // mappers defined on the previous topic
const App = ({ children }: React.PropsWithChildren): React.ReactElement => {
const debugMode = true; // Enable debug mode
return (
<FormGroupContextProvider mappers={mappers} debugMode={debugMode}>
{children}
</FormGroupContextProvider>
);
};
export default App;You now can use in your form the mapped components with names input and dropdown.
Also note the data in TMapper.events. There you can map up to five form functionalities per component
| Key | Functionality | | --------------- | -------------------------------------------------------------------------------------------------------------------- | | getValue | The name of your component prop that will give back the selected value. | | setValue | Prop name that receives the value | | setErrorMessage | Component prop name to receive an error message in case this field will have error and error message is configured | | setErrorState | Component prop name to receive a boolean indicating if the field has an error or not according to the configurations | | onBlur | Prop name that is called when field is blured | | onFocus | Prop name that is called when field is focused | | onKeyUp | Prop name that is called when user releases a key on field | | onKeyDown | Prop name that is called when user presses a key on field |
[DEPRECIATED] You can also use default prop names for functionalities like:
import Input from 'Components/Input';
import Dropdown from 'Components/Dropdown';
const Mappings = {
inputForm: { component: Input },
dropdownForm: { component: Dropdown },
};
const propsMapping = {
__default__: {
getValue: 'onChangeCallback',
setValue: 'data',
setErrorMessage: 'errorMessageArray',
onBlur: 'onBlurCallback',
onFocus: 'onFocusCallback',
onKeyUp: 'onKeyUpCallback',
onKeyDown: 'onKeyDownCallback',
},
};[DEPRECIATED] This will make form search for those names in all your components that do not have split mapping.
useFormGroupContext
Hook that facilitates the use of the FormGroupContext context in functional components.
- Checks if the context is set or creates an isolated context that will only be accessible on the component that is defined.
- Returns the context.
What comes from
addForm: Function to add a form to the group.getForm: Function to obtain a specific form from the group.removeForm: Function to remove a form from the group.formGroupInstance: Instance of the form group.printFormGroupInstance: Function to print the form group instance.submitMultipleFormsByIndex: Function to submit multiple forms by index.
type TFormContext = {
addForm: (payload: { key: string; formInstance: TFormCore }) => void;
getForm: (payload: { key: string }) => FormCore | undefined;
removeForm: (payload: { key: string }) => void;
formGroupInstance: TFormGroup;
printFormGroupInstance: () => void;
submitMultipleFormsByIndex: (indexes: string[]) => TFormValues;
};Example
import React from 'react';
import { useFormGroupContext } from '@bolttech/form-engine'; // Import the previously created hook
const FormComponent = (): React.ReactElement => {
const { addForm, removeForm, getForm, printFormGroupInstance, submitMultipleFormsByIndex, debugMode } = useFormGroupContext();
const handleAddForm = () => {
const key = 'form1';
const formInstance = new FormCore(); // Assuming FormCore is an existing class
addForm({ key, formInstance });
};
const handleRemoveForm = () => {
const key = 'form1';
removeForm({ key });
};
const handleGetForm = () => {
const key = 'form1';
const form = getForm({ key });
console.log(form);
};
const handleSubmitForms = () => {
const indexes = ['form1', 'form2'];
const formValues = submitMultipleFormsByIndex(indexes);
console.log(formValues);
};
return (
<div>
<button onClick={handleAddForm}>Add Form</button>
<button onClick={handleRemoveForm}>Remove Form</button>
<button onClick={handleGetForm}>Get Form</button>
<button onClick={handleSubmitForms}>Submit Forms</button>
<button onClick={printFormGroupInstance}>Print Form Group Instance</button>
{debugMode && <p>Debug mode is enabled</p>}
</div>
);
};
export default FormComponent;Form
After configuring the provider, <Form /> components lets you render a form
Props
| Prop | Type | Description | | ----------------------------------- | ---------------------------------------------------------------------------------- | ------------ | | [DEPRECIATED] disable | boolean | Disable all form inputs. It will use the default htm disable attribute | | [DEPRECIATED] group | string | Form group identifier. Used be able to group several forms and then get data with useGroupForm. One will be generated as default if omitted | | index | string | Form identified. One will be generated as default if omitted | | [DEPRECIATED] hooks | THooks | Provide functions to run on certain life-cycle events | | iVars | Object | One object with internal variables to be used in form with data binding | | initialValues | Object | Object with form initial values that will map to a field. | | Schema | TSchema | Form Schema | | [DEPRECIATED] autoComplete | string | HTML autocomplete | | className | string | Allow to style form | | onSubmit | callback(TFormValues) | Will be called when there is a submit action in the form | | onData | callback(TFormData) | Will be called when any field data change. The arguments will let you know which field changed and the field configuration | | onBlur | callback(TFieldEvent) | Will be called when any field blured. The arguments will let you know which field blured and the field configuration | | onFocus | callback(TFieldEvent) | Will be called when any field focused change. The arguments will let you know which field focused and the field configuration | | onMount | callback(TFormValues,TComponent, TField) | Will be called when some field mounted. Its called with the field that information that mounted. | | [DEPRECIATED] onStep | callback(TFormValues) | Called when a form step changed | | [DEPRECIATED] onLog | callback(TLoggingEvent) | Called on each log, if the logging is enabled | | [DEPRECIATED] onScopeChange | onScopeChange?(scope: TScope, namespace: string, key: string): void; | Called everything scope change with the changing information (namespace and key) and the changed scope | | onClick | onClick(TFieldEvent) | Callback function that runs on each component click | | onApiResponse | onApiResponse(TFieldEvent) | Callback function that runs on each component after api call. | | [DEPRECIATED] onFieldRehydrate | onFieldRehydrate?(values: TFormValues, component: TComponent, field: TField): void | This callback is called whenever some form field was rehydrated | | [DEPRECIATED] renderLoading | renderLoading?(): ReactElement; | Component to render while the schema has not rendered | | [DEPRECIATED] onFormMount | onFormMount?(values: TFormValues): void; | Called when the form finished mounted | | [DEPRECIATED] formattedDataDefaults | Object | Some default data to fields when they are undefined | | [DEPRECIATED] submitOnValidOnly | boolean | Boolean indicating if form can be submitted even if it is invalid | | [DEPRECIATED] renderFieldWrapper | renderFieldWrapper(component: TComponent, children: ReactElement[]) | Function that allows to insert a wrapper in place of a component or wrapping the component | | onApiRequest | onApiRequest(TFieldEvent) | Callback function that runs when an api call starts | | onChange | onFieldChange(TFieldEvent) | Callback function that runs on each component value changes | onKeyDown | onKeyDown(TFieldEvent) | Callback function that runs on each key down event | | onKeyUp | onKeyUp(TFieldEvent) | Callback function that runs on each key up event | | onCleared | onCleared(TFieldEvent) | Callback function that runs on a value that has been changed by resetValues event | | onUnmount | onUnmount(TFieldEvent) | Callback function that runs when a field is unmounted or hidden by a visibility condition rule (use with caution) |
Example
A simple example of rendering a basic form
<Form schema={schema} />Submit Form
In order to submit a form you need to have a button with the prop type submit and set a callback function on onSubmit Form prop
Example:
const schema = {
index: 'form1',
components: [
{
name: 'firstName',
component: 'input',
props: {
label: 'first name',
},
},
{
name: 'lastName',
component: 'input',
props: {
label: 'lase name',
},
},
{
name: 'submitButton',
component: 'button',
props: {
type: 'submit',
text: 'submit form',
},
},
],
};
const Comp = () => {
const handleSubmit = (payload: TFormValues<unknown>) => {
const values = payload.values;
userService
.addNewUser(values)
.then((res) => {
router.push(`/plans?hash=${res.hash}`);
})
.catch((e) => {
logService.push(e);
router.push(`/errorPage`);
});
};
return <Form schema={schema} onSubmit={handleSubmit} />;
};This is a sample on how to handle a form submission, you can adapt to any use case, and also set the onSubmit callback function on the useForm hook, but when you
have a Form component, it's preferable to set the onSubmit callback function onto the Form prop, the hook is preferrable to asFormFieldBuilder fields that doesn't
have a Form component and event callback functions needs to be setted
schema
Schema is the structure of the form, it will contain the logic to be rendered and configurations of the fields to apply dynamic logic
| Prop | Type | Description | | ----------------------------------------------------------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------- | | index | string | unique form id to handle multiple form on form group | | action? | string | WIP: HTML form native action property to handle native form submissions | | method? | string | WIP: HTML form native method property to handle native form submissions | | config? | TSchemaFormConfig | Optional configuration object to set api and events debounce time | | initialValues? | Record<string, unknown> | initial values to be loaded on the form | | iVars? | Record<string, unknown> | dynamic values that can be changed externally to be used onto the form | | components? | IComponentSchema[] | components to be rendered defined on the mappers |
this root configuration can be defined onto the Form component except the components
Example
const schema: IFormSchema = {
index: 'form1',
components: [
{
component: 'input',
name: 'input1',
props: {
label: 'input1',
},
},
{
component: 'input',
name: 'input2',
props: {
label: 'input2',
},
},
],
};schema components
Schema components contains the information of the component that will be rendered and the configurations he will exectute
| Prop | Type | Description | | ------------------------------------------------------------------------------------------------------------------------------ | -------------------- | ------------------------------------------------------------------------------------------- | | component | string | component name defined on schema to render the correspondent component | | props? | TProps | props of the component ex: label | | name | string | unique id to identify the field onto form-engine | | nameToSubmit? | string | dot notation to submit a custom path to the component value ex: 'person.profile.firstName' | | validations? | TValidations | validations configuration described below | | api? | TApiEvent | api configuration described below | | visibilityConditions? | TVisibility[] | visibilityConditions configuration described below | | resetValues? | TResetValueMethods[] | resetValues configuration described below | | formatters? | TFormatters | formatters configuration described below | | masks? | TMasks | masks configuration described below | | children? | IComponentSchema[] | nested components to be rendered (if the current parent component accepts child components) |
Example
{
component: 'input',
name: 'input1',
props: {
label: 'input1',
},
nameToSubmit: 'person.profile.firstName',
validations: {
methods: {
required: true,
},
eventMessages: {
ON_FIELD_CHANGE: ['required'],
},
messages: {
required: 'Value is required',
},
},
api: {
defaultConfig: {
config: {
method: 'GET',
url: 'https://api.chucknorris.io/jokes/random',
resultPath: 'value',
},
events: ['ON_FIELD_MOUNT'],
},
},
visibilityConditions: [
{
validations: {
isNumber: true,
},
events: ['ON_FIELD_CHANGE'],
fields: ['input2'],
},
],
resetValues: [{
validations: {
isNumber: true,
},
events: ['ON_FIELD_CHANGE'],
fields: ['input2'],
resettledValue: ['resettledValue from input1'],
}]
}Check the TSDocs from IComponentSchema on form-engine-core
formatters
formatters are methods that will format the input inserted on any field, they will format a value, regardless the event type.
| Prop | Type | Description | | ------------------------------------------------------------------------------------------------------------ | ------------------------- | ---------------------------------------------------------------------------------------------------------------- | | callback? | (value) => void | Custom formatter callback function | | capitalize? | boolean | Capitalize the value | | dotEvery3chars? | boolean | Add a dot every 3 characters | | gapsCreditCard | string[] | Gaps to insert in credit card numbers | | maxLength? | number | Truncates the input value to a specified maximum length if necessary | | onlyFloatNumber? | TCurrencyMask | Allow only float numbers with specific precision and decimal | | onlyLetters? | boolean | Allow only letters | | onlyNumbers? | boolean | Allow only numbers | | regex? | string | Regular expression for formatting | | splitter? | TSplitterFormatterValue[] | Splitter values for formatting | | trim? | boolean | Removes whitespace from both ends of this string and returns a new string, without modifying the original string | | uppercase? | boolean | Convert the value to uppercase |
Avaliable formatters
Check the TSDocs from TFormatters on form-engine-core
masks
masks are methods that will format the input inserted on any field, they will show to the user a formatted value, but the submission value will be the original input of the user.
| Prop | Type | Description | | --------------------------------------------------------------------------------------------------------- | ---------------------- | ------------------------------------------------------ | | card? | boolean | Mask for card values | | cardDate? | boolean | Mask for card date values | | currency? | TCurrencyMask | Mask for currency values | | custom | string | Custom mask pattern | | fein? | boolean | Mask for FEIN (Federal Employer Identification Number) | | generic? | TMaskGeneric[] | Array of generic masks | | replaceAll? | string | Value to replace all matches | | secureCreditCard? | boolean | Mask for securing credit card values | | callback? | (value, masks) => void | Custom mask callback function |
Avaliable masks
Check the TSDocs from TMasks on form-engine-core
From v2 to v3
//v2
const formatters = {
ON_FIELD_MOUNT: {
upperCase: true,
},
ON_FIELD_CHANGE: {
upperCase: true,
},
};
//v3
const formatters = {
upperCase: true,
};nameToSubmit
nameToSubmit is a component property that will set the submit value to a custom dot notation path or key
Example
const component = {
component: 'input'
name: 'input1'
nameToSubmit: 'person.profile.firstName'
}when calling the onSubmit or onData the field section of this field will output:
{
"person": {
"profile": {
"firstName": "inserted value from input1"
}
}
}props
props let you add any prop the component you are using from the mappers that exists on the component
Example
const component = {
component: 'input'
name: 'input1'
props: {
label: 'input1 label'
}
}If the mapper of input has the label prop avaliable, it will be set with input1 label value
validations
validations let you set rules in order to validate a field, then show errorMessages based on an event occured
| Prop | Type | Description | | -------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------- | | methods | TSchemaValidation | validations rules to be used to validate the field | | eventMessages? | Partial<Record<TEvents, Partial[]>> | object with the event occured, and the messages to display on the occured event | | messages? | TErrorMessages | object with the validations and the respective error message to display |
Avaliable validations
Check the TSDocs from TValidationMethods on form-engine-core
From v2 to v3
//v2
const component: {
component: 'input';
name: 'input1';
validations: {
ON_FIELD_BLUR: {
required: true;
};
ON_FIELD_CHANGE: {
regex: '^[0-9]{2}/[0-9]{2}$';
};
errorMessages: {
required: 'field required';
regex: 'invalid format';
};
};
};
//v3
const validations: {
methods: {
required: true;
regex: '^[0-9]{2}/[0-9]{2}$';
};
eventMessages: {
ON_FIELD_BLUR: ['required'];
ON_FIELD_CHANGE: ['regex'];
};
messages: {
required: 'field required';
regex: 'invalid format';
};
};named validations
if you want to make a name validation, instead of using a TValidationMethods, you can write a custom name with TValidationMethods inside, ex:
const validations: {
methods: {
custom1: {
regex: '^[0-5]{4}/[0-3]{6}$';
};
custom2: {
regex: '^[0-9]{2}/[0-9]{2}$';
};
};
eventMessages: {
ON_FIELD_BLUR: ['custom1'];
ON_FIELD_CHANGE: ['custom2'];
};
messages: {
custom1: 'field required';
custom2: 'invalid format';
};
};This is useful if you want to make more than one rule of the same TValidationMethods,
default error message
If you don't want to specify each error message for each method, you can use defaulton messages property, this message will appear regardless the validation method
and only one method that will fail will display the message, you still need to set on eventMessages which events and methods will trigger an error message.
api
Api let's you make a request and use the response values onto fields
The configuration is as it follows:
| Prop | Type | Description | | -------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | defaultConfig? | TEvent | this is the default config, preferred if you only have 1 API request on a field | | configs? | Record<string, TEvent> | this is a named config, preferred if you have more than 1 API request on a field, you set a key and an API config |
Each config you opt to use, needs to be filled with an API configuration, the configuration is as it follows:
| Prop | Type | Description | | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------- | | method | 'GET' or 'POST' | HTTP method (only GET or POST) | | url | string | Request url ex: http://mockapi.org | | body? | Record<string, unknown> | Request body (only POST requests) | | headers? | OutgoingHttpHeaders | Avaliable HTTP headers | | queryParams? | Record<string,string> | url query params (to be appended to the already existing ones) | | resultPath? | string | response dot notation path to the value needed from the response | | fallbackValue? | unknown | default value to return if the API returns error | | preConditions? | TSchemaValidation | validations to occur before the request is made (check validations section) | | blockRequestWhenInvalid? | boolean | flag to only request the api config if the field is valid | | transform? | { callback:(payload) => unknown } | custom function to be passed as callback to transform the request in any other format |
From v2 to v3
Instead of setting scope on the api config, you use a config with a key name that you want to use as scope, or you can just use defaultConfig and set the same
structure as you pass to the config without a key name
//v2
const api = {
ON_FIELD_BLUR: [
{
method: 'GET',
url: 'https://api.chucknorris.io/jokes/random',
scope: 'chuck',
},
],
ON_FIELD_CHANGE: [
{
method: 'GET',
url: 'https://api.chucknorris.io/jokes/random',
scope: 'chuck',
},
],
};
//v3
const api = {
config: {
chuck: {
config: {
method: 'GET',
url: 'https://api.chucknorris.io/jokes/random',
},
events: ['ON_FIELD_BLUR', 'ON_FIELD_CHANGE'],
},
},
};the API result is commonly used with templating, check templating section
resetValues
resetValues lets you change input values with the same rules as validations
| Prop | Type | Description | | --------------------------------------------------------------------------------------------- | -------------------- | ---------------------------------------------------------------------------------- | | validations | TSchemaValidation | validations rules to be validated to reset the value to the configuration provided | | fields | string[] or string | field or fields that will recieve the resettled value | | events | Partial[] | events that will trigger the validation | | resettledValue | unknown[] or unknown | value or values to be set on the specified fields |
if the event occurs and all the validations returns true the resettled value will trigger and the fields specified will be filled with the resettledValue values, also, the event ON_FIELD_CLEARED is triggered on the fields that gets the resettled value instead of ON_FIELD_CHANGE.
from v2 to v3
clearFields is changed to resetValues
//v2
const clearFields = {
ON_FIELD_CLICK: [
{
fields: ['input1', 'input2', 'dropdown'],
clearedValue: ['', 'Value has change', 'all'],
},
],
ON_FIELD_BLUR: [
{
fields: ['input1', 'input2', 'dropdown'],
clearedValue: ['', 'Value has change', 'all'],
},
],
};
//v3
const resetValues = [
{
fields: ['input1', 'input2', 'dropdown'],
resettledValue: ['', 'Value has change', 'all'],
events: ['ON_FIELD_CLICK', 'ON_FIELD_BLUR'],
},
];visibilityConditions
visibilityConditions will show or hide fields based on rules, the structure is similar as the resetValues, but instead, you will set the fields to be shown or hidden
| Prop | Type | Description | | --------------- | ------------------ | ---------------------------------------------------------------------------------- | | showOnlyIfTrue? | boolean | shows the fields specified is condition is true | | validations | TSchemaValidation | validations rules to be validated to reset the value to the configuration provided | | fields | string[] or string | field or fields that will be shown or hidden | | events | Partial[] | events that will trigger the validation |
From v2 to v3
//v2
const visibilityConditions = {
ON_FIELD_MOUNT: [
{
validations: {
value: true,
},
fieldNames: ['roofUpdatedYear'],
},
],
ON_FIELD_CHANGE: [
{
validations: {
value: true,
},
fieldNames: ['roofUpdatedYear'],
},
],
};
//v3
const visibilityConditions = [
{
validations: {
value: true,
},
fields: 'roofUpdatedYear',
events: ['ON_FIELD_MOUNT', 'ON_FIELD_CHANGE'],
},
];resetPropertyValues
resetPropertyValues will change a property value based on validation rules
WARNING: do not rely on this to make mutations on your properties, templating already is a powerful tool and with this you can destroy some schema configurations accidentaly, this is a last resort schema manipulation tool to solve some edge cases with API requests callbacks handling
| Prop | Type | Description | | -------------- | -------------------------------------------- | -------------------------------------------------------------- | | property | typeof ALLOWED_RESET_PROPS_MUTATIONS[number] | property to be changed, ex: api, resetValues, etc.. | | path | string | path where the property to be changed is located | | field | string | field that will recieve the property change | | resettledValue | unknown | value to be replaced onto the property | | validations | TSchemaValidation | validations rules to be validated to change the property value | | events | Partial[] | events to listen to apply this change |
example:
this will change the api.named.chuck property onto field postalCode when the ON_FIELD_CHANGE event occurs,
will change the content to: { status: null, response: ''}
resetPropertyValues: [
{
property: 'api',
path: 'named.chuck',
events: ['ON_FIELD_CHANGE'],
field: 'postalCode',
resettledValue: {
status: null,
response: '',
},
validations: {
bool: false,
},
},
];visibility
visibility prop is used to initiate the component with an initial visibility flag, before visibilityConditions take place, used on SSR
persistValue
persistValue is a flag that deremines if the field gets hidden, the moment it comes back visible, it will hold the previous value or not
templating
templating let's you use field properties or iVars as values of other properties
Templates separates on two scopes:
| Scope | Description | | ------ | --------------------------- | | fields | any property from a field | | iVars | any iVar passed to the form |
From v2 to v3
getting an iVar in v2:
${globals.ivarsample}
getting an iVar in v3:
${iVars.ivarsample}
api scope now doesn't exist and the api response will be taken from the field
getting api response from field field1 in v2:
${api.chuck.value}
getting api response from field field1 in v3:
${fields.field1.api.chuck.response.value}
Examples:
Templates start with the scope term, are defined with ${} syntax and use dot notation to get the property you want,
Examples:
${fields.field1.value} this will get the current value of a field
${fields.field1.api.default.response||[]} this will get the response of a field api or an empty array
${fields.field1.props.label} this will get the label prop defined on the component schema prop
${fields.field1.props.label||fields.field1.props.description} this will get the label OR description defined on the component schema props
${fields.field1.props.label} and ${fields.field1.props.description} this will concatenate label AND description defined on the component schema props in a string
hooks
useForm
useForm is used to register callback functions instead of passing them to the Form props,
useForm({ id: 'form1', onData: (data) => console.log(data) });
return <Form index={'form1'} schema={schema}>Each time a data event occurs, the callback function passed on onData executes, allowing to run additional code outside the form-engine lifecycle
Also, there's an additional property to be passed on this hook in order to event record occurs on certain scenarios
useForm({ id: 'form1', onData: (data) => console.log(data) },[visible]);
return visible && <Form index={'form1'} schema={schema}>If you happen to have a conditional form render inside the react jsx implementation, you need to add it to the dependency array, or, if you can pass the respective callback to the form props like this:
<Form index={'form1'} schema={schema} onData={(data) => console.log(data)} />The avalialbe callback methods are:
| method | payload | description | | ------------- | ---------------------- | -------------------------------------------------------------------- | | onChange | TFieldEvent | basic event returning this type if this event occurs, (check TSDocs) | | onBlur | TFieldEvent | same as above | | onFocus | TFieldEvent | same as above | | onKeyDown | TFieldEvent | same as above | | onKeyUp | TFieldEvent | same as above | | onClick | TFieldEvent | same as above | | onApiResponse | TFieldEvent | event occuring when a api response is ready | | onApiRequest | TFieldEvent | event occuring when a api resquest is started | | onMount | TFieldEvent | event occuring when a field is mounted or set visible | | onUnmount | TFieldEvent | event occuring when a field is unmounted or hidden | | onCleared | TFieldEvent | event occuring when the field value is set with resetValues | | onFormMount | TFormValues | event occuring on form mount | | onData | TFormData | event occuring when a value is changing via input or logic | | onSubmit | TFormValues | event occuring when pressing the submit button defined on the form | | onValid | TFormValidationPayload | event occuring when validation status changes on the form |
useFormGroup
useFormGroup({ ids: ['form1', 'form2'], onData: (payload) => console.log(payload) }, [deps]);As useForm, useFormGroup serves the same purpose, but the difference is that it handles multiple forms and has limited callback functions to set:
| method | payload | description | | -------- | --------------------------------- | ----------------------------------------------------------- | | onData | TFormGroupOnDataEventPayload | event occurring when a value is changing via input or logic | | onValid | TFormGroupOnValidEventPayload | event occurring when validation status changes on the form | | onSubmit | TFormGroupOnSubmitEventPayload | event occurring when form submission is trigger |
asFormField
Currently on development process, allows to build a schema with react components instead of a json schema
AsFormFieldBuilder
This component allows to create form fields with the functionality of form-engine without a form schema or a Form component,
they will be identified by it's id on the formGroup context and they will interact with each other by the same id.
Also, they don't require component mapping, so the component mapping can be done on this component by passing the mapper by it's props:
Ex:
<AsFormFieldBuilder
mapper={{
component: Input,
events: {
getValue: 'onChange',
setValue: 'value',
setErrorMessage: 'errorMessage',
onBlur: 'onBlur',
onFocus: 'onFocus',
},
valueChangeEvent: (event: unknown) => {
return (event as ChangeEvent<HTMLInputElement>).target.value;
}
}}
props={{
label: 'Input label',
}}
formIndex={'form1'}
name={'asFormField'}
validations={{
methods: {
required: true,
},
eventMessages: {
ON_FIELD_CHANGE: ['required'],
},
messages: {
required: 'its required',
},
}}
></AsFormFieldBuilder>Other than schema component properties like validations, api, etc.., it has additional properties to define the component, the associated form id and the name
| method | type | description | | --------- | ---------- | ------------------------------------------------------------------------------------------------------------------------ | | mapper | TMapper | mapper configuration to define the component | | name | string | field name to be identified on the form | | formIndex | string | index of the form to be identified on the formGroup | | component | string | if mappers is provided from the formgroup context, you can assign the mapper by it's name instead of whole mapper config |
AsFormFieldRepeater
Component adapter to aid managing multiple forms that shares the same inputs
Props:
| Attr | Type | Description | | ----------------- | --------------------------------------------------------- | -------------------------------------------------------------------------- | | RepeaterComponent | ElementType<{ formIndex: string }> | Component with form schema or AsFormFieldBuilder elements | | addFieldName | string | name of the button in the RepeaterComponent to add forms | | removeFieldName | string | name of the button in the RepeaterComponent to remove forms | | existingElements | Record<string, unknown>[] | existing values emmitted from stateUpdater to restore previous used values | | initialElements | number | elements to be pre-rendered when the form is presented | | stateUpdater | (payload: TFormGroupOnDataEventPayload) => void; | callback function that reacts to RepeaterComponet values changes | | formPrefix | string | prefix for form names ex, prefix: foo, forms: ["foo1","foo2","foo3"] | | RepeaterFooter | ElementType<{ formIndex: string }> | Component with a button to add forms on the last position |
Common use case for this Adapter is to manage multiple forms that collects the same data ex: multiple person personal data
Example
RepeaterComponent
const FormElement = ({ formIndex }: { formIndex: string }) => {
return (
<>
<AsFormFieldBuilder formIndex={formIndex} name="foo" component="input" props={{ label: 'foo' }} />
<AsFormFieldBuilder formIndex={formIndex} name="bar" component="input" props={{ label: 'bar' }} />
<AsFormFieldBuilder
formIndex={formIndex}
name="addForm"
component="button"
props={{
text: 'add element',
}}
/>
<AsFormFieldBuilder
formIndex={formIndex}
name="removeForm"
component="button"
props={{
text: 'remove element',
}}
/>
</>
);
};Important notes when developing this component is that it needs to receive an object with a key formIndex
Optionally, but to add form management functionality, add two buttons with ON_FIELD_CLICK event capture (can't be of type submit) both that Field button names will be needed on the next step
RepeaterFooter
Optionally, you can develop a footer component with a button that will be added the bottom of the repeated forms and when you press that button will add a form at the bottom of the list
It's props needs to be an objet with a formIndex key, the button needs to have ON_FIELD_CLICK event capture (can't be of type submit) Note: the button name needs to be different from the names you gave to the buttons you are passing on the RepeaterComponent
const FormElementFooter = ({ formIndex }: { formIndex: string }) => {
return (
<AsFormFieldBuilder
formIndex={formIndex}
name="addFormBelow"
component="button"
props={{
text: 'add element below',
}}
/>
);
};AsFormFieldRepeater
Set the AsFormFieldRepeater adapter with the element you created above and the names that you gave to the button fields
<AsFormFieldRepeater
RepeaterComponent={FormElement}
RepeaterFooter={FormElementFooter}
addFieldName="addForm"
removeFieldName="removeForm"
formPrefix="insured"
stateUpdater={(payload) => {
console.log(payload);
}}
/>RepeaterComponent and RepeaterFooter you set the elements created above
addFieldName you set the name to the button that will add a form on the position it's being clicked
removeFieldName you set the name to the button that will remove a form on the position it's being clicked
formPrefix the prefix for the forms emmited on stateUpdater enumerated
stateUpdater callback function that will receive the form values (similar to onData)
