Skip to content

API Properties

The API provides key properties that help developers control and operate forms. These properties give you comprehensive control over forms, allowing you to operate and configure forms flexibly according to different business scenarios.

Form Generation Rules

The rule property represents the generation rule list for the current form, defining the structure and configuration of all components in the form. By modifying the rule, you can dynamically adjust the layout and content of the form.

typescript
type rule = Rule[]
  • Example:
js
// Get generation rules of the current form
const rules = api.rule;
// Modify title of a component
rules[0].title = 'New Title';

Form Global Configuration

config is the global configuration object for the current form, containing all basic settings such as button configuration and layout options. api.options is an alias for config.

typescript
type config = Object
  • Example:
js
// Get global configuration of the current form
const options = api.config;
// Update form configuration
api.updateOptions({ submitBtn: false });

Form Data

The form property is the data object for the current form, containing values of all fields. This property is two-way bound, meaning that modifying the form object directly updates form data, and changes in form data are reflected synchronously in the form object.

typescript
type form = { [field:string]:any }
  • Example:
js
// Get form data
const formData = api.form;
// Modify value of a field in the form
formData.goods_name = 'huawei';
// Get form data when submitting the form
api.onSubmit((formData) => {
  console.log('Submitted form data:', formData);
});

This property is two-way bound

Form Index

The index property returns the index of the current form in the sub-form (group). It's used in nested form scenarios to determine the position of the current form among sibling sub-forms.

typescript
type index = number | undefined;
  • Example:
js
// Get index of the current form in the sub-form
const formIndex = api.index;
// Use index for operations
console.log('Index of current form in sub-form:', formIndex);

Sibling Form APIs

The siblings property returns all form API objects in the sub-form (group) where the current form is located. It's used in nested form scenarios to get APIs of sibling forms, enabling batch operations or coordinated operations.

typescript
type siblings = Api[] | undefined;
  • Example:
js
// Get all form API objects in the sub-form where the current form is located
const siblingApis = api.siblings;
// Traverse all sibling forms and perform operations
if (siblingApis) {
    siblingApis.forEach(siblingApi => {
        // For example, validate all sibling forms
        siblingApi.validate();
    });
}

Top-Level Form API

The top property is used to get the top-level form API object of the current form. In nested form structures, top always points to the outermost form API.

typescript
type top = Api | undefined;
  • Example:
js
// Get top-level form API object
const topFormApi = api.top;
// Reload rules of the top-level form
if (topFormApi) {
  topFormApi.submit(); // Submit parent form
}

Sub-Form APIs

The children property is used to get the API object list of all sub-forms under the current form. This is very useful for operating multiple sub-forms nested in the current form.

typescript
type children = Api[];
  • Example:
js
// Get API objects of all sub-forms
const subFormApis = api.children;
// Traverse all sub-forms and validate them
subFormApis.forEach(subApi => {
  subApi.validate();
});

Examples

Cascading Operations on Parent and Child Forms

In a multi-level nested form, certain operations need to affect the state of the parent form. For example, when field validation in a sub-form passes, the parent form needs to be automatically submitted.

js
const subFormApi = api.children[0]; // Get first sub-form API
subFormApi.onSubmit((formData) => {
    if (subFormApi.validate()) {
        const parentApi = api.parent;
        if (parentApi) {
            parentApi.submit(); // Submit parent form after validation passes
        }
    }
});

Dynamically Update Form Configuration

In a multi-role management system, different user roles require different form layouts and configurations. For example, administrators have permission to view and edit all fields, while regular users can only view some fields.

js
const userRole = api.getData('userRole', 'user'); // Get current user role from external data
if (userRole === 'admin') {
    api.updateOptions({ form: { inline: false } }); // Administrators have a more relaxed form layout
} else {
    api.updateOptions({ form: { inline: true } }); // Regular users use a compact form layout
}
api.refresh(); // Ensure configuration takes effect immediately

Batch Operations on Sub-Forms

In a complex form, multiple sub-forms may be nested, each with independent validation logic. Before submitting the main form, you need to ensure that all sub-forms have passed validation.

js
const subFormApis = api.children; // Get all sub-form APIs
let allValid = true;
subFormApis.forEach(subApi => {
    if (!subApi.validate()) {
        allValid = false;
    }
});
if (allValid) {
    api.submit(); // Submit main form after all sub-forms pass validation
} else {
    console.log('Some sub-forms failed validation');
}

Real-Time Update and Processing of Form Data

In an order settlement system, after the user enters the order amount, the system needs to calculate and display the tax amount and total amount in real time. Through the form property, you can update and synchronize related field data in the form in real time.

js
api.on('change', (field, value) => {
    if(field === 'amount' || field === 'tax') {
        const taxRate = 0.1;
        api.form.tax = api.form.amount * taxRate;
        api.form.total = api.form.amount + api.form.tax;
        api.refresh(); // Refresh form to display tax amount and total amount
    }
});

Nested Form Data Synchronization and Operations

In a complex nested form system, certain data from sub-forms needs to be synchronized to the parent form in real time. Through the parent property, you can automatically update parent form data when sub-form data changes.

js
api.on('change', (field, value) => {
    if(field === 'child') {
        const parentFormApi = api.parent;
        if (parentFormApi) {
            parentFormApi.setValue('childData', value); // Pass sub-form data to parent form
            parentFormApi.refresh(); // Refresh parent form to apply new data
        } 
    }
});

Batch Validation and Submission of Sub-Forms

In a scenario that requires independent validation of multiple sub-forms, you can use the children property to batch operate all sub-forms, ensuring that each sub-form passes validation before unified submission.

js
const subFormApis = api.children; // Get all sub-form API objects
Promise.all(subFormApis.map(subApi => subApi.validate())).then(() => {
    api.submit(); // Submit main form after all sub-forms pass validation
}).catch(() => {
    console.error('Some sub-form failed validation');
});

Dynamically Generate or Adjust Form Fields Based on Permissions

In a permission-controlled system, different users may have different operation permissions. For example, some users can only view form data but cannot perform editing operations. When generating forms, you can dynamically adjust the editable state of fields based on user permissions.

js
const userPermissions = api.getData('userPermissions', {}); // Get user permission data
api.rule.forEach(rule => {
    if (!userPermissions.editableFields.includes(rule.field)) {
        rule.props.disabled = true; // Disable field if it is not editable
    }
});
api.refresh(); // Apply modified rules

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.