Skip to content

Form Operations

The API provides powerful form operation methods that enable developers to control and operate forms in different business scenarios. These methods cover form data processing, DOM operations, submission logic, and more.

Get Form Component vm/dom Element

The formEl method returns the Vue instance or DOM element of the entire form component.

typescript
type formEl = () => Vue|Document|undefined
  • Example:
js
const vm = api.formEl();
console.log(vm);

Get FormItem Component vm/dom Element

The wrapEl method returns the Vue instance or DOM element of the FormItem component for the specified field.

typescript
type wrapEl = (field:string) => Vue|Document|undefined
  • Example:
js
const vm = api.wrapEl('goods_name');
console.log(vm);

Get Form Data

The formData method returns data for all fields or specific fields in the form. The return value is a snapshot of the data and is not two-way bound.

typescript
interface formData {
    //Get all data
    (): {[field:string]:any }
    //Get data of some fields
    (field:string[]): {[field:string]:any }
}
  • Example:
js
const allData = api.formData();
console.log('All form data:', allData);
const specificData = api.formData(['goods_name', 'price']);
console.log('Partial form data:', specificData);

Form Value Change Status

The changeStatus method checks whether values in the form have changed. It returns a boolean indicating whether the form has been modified by the user since it was loaded.

typescript
type changeStatus = ()=>Boolean
  • Example:
js
const hasChanged = api.changeStatus();
if (hasChanged) {
  console.log('Form data has been modified');
} else {
  console.log('Form data has not been modified');
}

Clear Change Status

The clearChangeStatus method clears the change status of the form. After calling this method, changeStatus will return false.

typescript
type clearChangeStatus = ()=>void
  • Example:
js
api.clearChangeStatus();
console.log('Form change status has been cleared');

Modify Submit Button

The submitBtnProps method dynamically modifies properties of the form submit button, such as disabled state, loading state, or button text.

typescript
type submitBtnProps = (props:Object) => void
  • Example:
js
api.submitBtnProps({ disabled: true });
  • Shortcut Operations:

  • api.btn.loading(true) Set submit button to loading state

    • api.btn.disabled(true) Set submit button disabled state
    • api.btn.show(true) Set submit button display state

Modify Reset Button

The resetBtnProps method dynamically modifies properties of the form reset button, such as disabled state, loading state, or button text.

typescript
type resetBtnProps = ( props:Object) => void
  • Example:
js
api.resetBtnProps({ disabled: true });
  • Shortcut Operations:

  • api.resetBtn.loading(true) Set reset button to loading state

    • api.resetBtn.disabled(true) Set reset button disabled state
    • api.resetBtn.show(true) Set reset button display state

Update Form Configuration

The updateOptions method dynamically updates global configuration options for the form. These configuration options include form layout, button configuration, validation rules, and more.

typescript
type updateOptions = (options:Object) => void
  • Example:
js
api.updateOptions({ form: { inline: true } });

Update Form Submit Event

The onSubmit method sets a custom submit event handler for the form. When the user submits the form, this callback function executes, and you can process form data in the callback.

typescript
type onSubmit = (callback:(formData:Object,api:Api)=>void) => void
  • Example:
js
api.onSubmit((formData, api) => {
  console.log('Form submitted data:', formData);
  // Custom submit logic
});

Refresh Form Configuration

The refreshOptions method manually refreshes configuration options for the form, ensuring that configuration changes take effect immediately.

typescript
type refreshOptions = ()=>void
  • Example:
js
api.refreshOptions();
console.log('Form configuration has been refreshed');

Refresh Form Rendering

The refresh method manually refreshes the rendering state of the form. This is useful when form content needs to be dynamically updated.

typescript
type refresh = ()=>void
  • Example:
js
api.refresh();
console.log('Form rendering has been refreshed');

Hide Form

The hideForm method hides or shows the entire form. After the form is hidden, users won't be able to see or operate the form.

typescript
type hideForm = (hide:Boolean)=>void
  • Example:
js
api.hideForm(true); // Hide form
api.hideForm(false); // Show form

Reload Form

The reload method is used to reload the form. You can choose to use existing generation rules or pass in new generation rules to reload the form.

typescript
interface reload{
    ():void
    (rules:Rule[]):void
}
  • Example:
js
api.reload(); // Reload form with existing rules
api.reload(newRules); // Reload form with new rules

Callback After Form Rendering

The nextTick method executes a callback function after the form rendering is complete. It can be used to ensure that DOM operations are performed after rendering is complete.

typescript
type nextTick = (callback:Function) => void
  • Example:
js
api.nextTick(() => {
  console.log('Form rendering is complete');
  // Operations after rendering is complete
});

Auto Refresh

The nextRefresh method executes a callback function and then automatically refreshes form rendering. This is particularly useful when operations that affect form rendering are performed in the callback.

typescript
type nextRefresh = (callback:Function) => void
  • Example:
js
api.nextRefresh(() => {
  console.log('Form operation completed, refreshing form...');
  // Execute operations that affect form rendering
});

Submit Form

The submit method is used to manually submit the form, supporting passing in success and failure callback functions. Custom validation and data processing can be performed when submitting the form.

typescript
type submit = (
    success?: (formData: Object, $f: Api) => void,
    fail?: ($f: Api) => void
) => Promise<any>;
  • Example:
js
api.submit(
        (formData, api) => {
          console.log('Form submitted successfully:', formData);
          // Logic processing after submission
        },
        (api) => {
          console.log('Form submission failed');
          // Handling logic when validation fails
        }
).then(formData => {
  // Recommended
  console.log('Form submitted successfully:', formData);
  // Logic processing after submission
});

Get Form json Rules

The toJson method is used to convert form rules to a JSON string.

typescript
type toJson = () => string
  • Example:
js
const jsonString = api.toJson();
console.log('JSON string of form rules:', jsonString);

Examples

Dynamically Control State of Submit and Reset Buttons

During form submission, dynamically control the state of submit and reset buttons based on user operations. For example, disable buttons and show loading state when submitting the form, and restore button state after submission is complete.

js
fApi.onSubmit((formData) => {
    fApi.btn.loading(true); // Set submit button to loading state
    fApi.btn.disabled(true); // Disable submit button
    fApi.resetBtn.disabled(true); // Disable reset button
    // Simulate submit operation
    setTimeout(() => {
        fApi.btn.loading(false); // Cancel loading state
        fApi.btn.disabled(false); // Re-enable submit button
        fApi.resetBtn.disabled(false); // Re-enable reset button
        console.log('Form submitted successfully:', formData);
    }, 2000);
});

Real-Time Update of Form Global Configuration

In a multi-language supported form, dynamically update the form's global configuration based on the language selected by the user, such as form layout, label position, validation rules, etc.

js
const language = fApi.getValue('language');
if (language === 'en') {
    fApi.updateOptions({ form: { labelPosition: 'top' }, validation: { message: 'Field is required' } });
} else if (language === 'zh') {
    fApi.updateOptions({ form: { labelPosition: 'left' }, validation: { message: 'This field is required' } });
}

Export Form JSON Generation Rules for Saving or Reuse

In a form designer tool, users can edit the form structure in real time and export the JSON rules of the current form for saving or reuse in other projects.

js
const jsonRules = fApi.toJson(); // Export JSON rules in formatted way
console.log('Exported form rules:', jsonRules);
// Save exported JSON rules to server or local storage
saveFormConfig(jsonRules);

Dynamically Modify Field Rules of Group Based on User Selection

In a customer information form, different customer types (individual customers or corporate customers) need to fill in different information. By modifying sub-form rules, you can dynamically adjust form content to adapt to user selection.

js
// Get API object of sub-form
const customerInfoApi = fApi.getSubForm('customerInfo');
// Dynamically modify sub-form rules based on customer type
const customerType = fApi.getValue('customer_type');
if (customerType === 'individual') {
    customerInfoApi.updateRule('company_name', { hidden: true }); // Hide company name field
    customerInfoApi.updateRule('personal_id', { hidden: false }); // Show personal ID field
} else if (customerType === 'business') {
    customerInfoApi.updateRule('company_name', { hidden: false }); // Show company name field
    customerInfoApi.updateRule('personal_id', { hidden: true }); // Hide personal ID field
}
// Refresh sub-form to apply new rules
customerInfoApi.refresh();

Batch Modify Data in Sub-Forms

In a complex multi-product order form, users can batch update the status of sub-orders.

js
// Get API object array of all sub-order forms
const subOrderApis = fApi.getSubForm('subOrders');
// Batch modify status of all sub-orders
subOrderApis.forEach(api => {
    api.setValue('order_status', 'shipped'); // Set sub-order status to shipped
    api.sync('order_status'); // Sync status to sub-form display
});
// Refresh all sub-order forms
subOrderApis.forEach(api => {
    api.refresh();
});

Batch Modify Component Rules in Sub-Forms

In an order management system, each order may contain multiple products. Based on product type, you need to batch modify the display state, parameters, and validation rules of fields in all sub-order forms.

js
// Get API object array of all sub-order forms
const subOrderApis = fApi.getSubForm('subOrders');
// Batch modify parameters, display state, and validation rules of fields in sub-order forms
subOrderApis.forEach((api) => {
    const itemType = api.getValue('item_type'); // Get product type of current sub-order
    if (itemType === 'electronic') {
        api.updateRule({
            'warranty': { hidden: false, validate: [{ required: true, message: 'Warranty period cannot be empty' }] }, // Show warranty field and validate required
            'discount': { props: { min: 0, max: 10 } } // Limit discount range to 0-10%
        });
    } else if (itemType === 'furniture') {
        api.updateRule({
            'warranty': { hidden: true, validate: [{ required: false }] }, // Hide warranty field and cancel validation
            'discount': { props: { min: 0, max: 20 } } // Expand discount range to 0-20%
        });
    }
    // Refresh each sub-order form to apply new field rules
    api.refresh();
});

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