Skip to content

Component Associating External Data

In FormCreate, the loadData property lets you load data from local or external data sources and insert it into specific positions of form components. This feature is useful for handling dynamic form data.

This feature is internally implemented through custom property methods.

Loading Data

Use the loadData property to dynamically load option data from external data sources into form components, achieving asynchronous updates and dynamic binding of form options.

Type

ts
interface LoadDataEffectOption {
    // Data name
    attr: String;
    // Insertion position, default is `options`
    to?: String;
    // Whether to deep copy when loading, default is `false`
    copy?: boolean;
    // Whether to synchronously modify when data source changes, default is `true`
    watch?: boolean;
    // Whether to directly modify component rules, default is `false`
    modify: boolean;
}
type LoadData = LoadDataEffectOption | LoadDataEffectOption[];

Note

Set the copy property to deep copy data when loading to prevent side effects from data references.

When watch is true, changes in the data source automatically update form component data.

When assigning values to value, set modify to true, otherwise the assignment operation won't take effect.

To associate attribute values in objects, use nested properties through the rule.variableName.attributeName format.

Usage Method

  1. Write data through formCreate.setData method

Before using loadData, preload data through the formCreate.setData method:

js
formCreate.setData('labelOptions', [
    {label: 'Very easy to use', value: 0},
    {label: 'Very fast', value: 1},
    {label: 'Very efficient', value: 2},
    {label: 'Very comprehensive', value: 3},
  ])
  1. Configure corresponding data name in loadData

In form rules, use the loadData configuration item to load data:

js
const rule = {
    effect: {
        loadData: {
            // Data name
            attr: 'labelOptions',
            // Insertion position
            to: 'props.options'
        }
    }
}

Built-in Variables

FormCreate provides some built-in variables for getting data from different sources:

Variable NameDescription
$topFormGet data from outer form
$formGet data from form
$optionsGet data from form configuration
$cookieGet data from cookie
$localStorageGet data from localStorage
$sessionStorageGet data from sessionStorage
$mobileWhether currently on mobile
$previewWhether currently in preview mode

Example: Get the value of the name field in the form

ts
const rule = {
    effect: {
        loadData: {
            // Data name
            attr: '$form.name',
            // Insertion position
            to: 'value',
            //Directly modify component rules
            modify: true
        }
    }
}
//Or api.getData('$form.name');

Get token data from cookie

ts
const rule = {
    effect: {
        loadData: {
            // Data name
            attr: '$cookie.token',
            // Insertion position
            to: 'props.headers.token',
            //Directly modify component rules
            modify: true
        }
    }
}

API Introduction

setData

Mount custom data to make it available in forms, facilitating data sharing between components.

  • Type:
ts
type SetData = (name:string,value:any) => void;
  • Example:
js
 formCreate.setData('options',[
        {label:'Easy to use',value:0},
        {label:'Fast',value:1},
        {label:'Efficient',value:2},
        {label:'All-in-one',value:3},
 ]);

setDataDriver

Import custom data retrieval functions to retrieve data from external data sources based on specific logic.

  • Type:
ts
type SetDataDriver = (id: string, callback: (key: string) => any) => void;
  • Example:
js
formCreate.setDataDriver('$user', function(key) {
    return $store.state.user[key];
});

The setDataDriver method lets you specify a data driver function for forms, enabling form components to dynamically retrieve data. For example, retrieve user data from Vuex state management and display it in forms.

getData

Get custom data previously mounted through setData.

  • Type:
ts
type GetData = (name: string) => any;
  • Example:
js
const options = formCreate.getData('options');
console.log(options);

removeData

Remove custom data previously mounted through the setData method.

  • Type:
ts
type RemoveData = (name:string) => void;
  • Example:
js
formCreate.removeData('options');

refreshData

Manually refresh form rendering related to specific data, ensuring form component display and data remain synchronized.

  • Type:
ts
type RefreshData = (name:string) => void;
  • Example:
js
formCreate.refreshData('options');

Examples

Dynamically Load Form Options Based on User Role

In actual business, you may need to dynamically display different form options based on user roles. Use loadData combined with setData and setDataDriver to achieve this.

js
// Assume user roles are stored in Vuex
formCreate.setDataDriver('$roleOptions', function(key) {
    const role = $store.state.user.role;
    if (key === 'admin') {
        return $store.state.admin.role;
        // return [
        //     { label: 'Admin Option 1', value: 'admin_option_1' },
        //     { label: 'Admin Option 2', value: 'admin_option_2' }
        // ];
    } else {
        return $store.state.user.role;
        // return [
        //     { label: 'User Option 1', value: 'user_option_1' },
        //     { label: 'User Option 2', value: 'user_option_2' }
        // ];
    }
});


const rules = [
    {
        type: 'select',
        field: 'role_based_options',
        title: 'Select Based on Role',
        effect: {
            loadData: {
                attr: '$roleOptions.admin',
                to: 'options'
            }
        }
    }
];

Real-time Update Form Dependent on External Data Source

In complex enterprise applications, forms may need to depend on external data sources (such as inventory systems) for real-time data updates. Using refreshData ensures that data in forms always remains up-to-date.

js
// Periodically refresh inventory data from external system
setInterval(() => {
    fetch('/api/inventory')
        .then(res => res.json())
        .then(data => {
            formCreate.setData('inventoryOptions', data);
            formCreate.refreshData('inventoryOptions');
        });
}, 60000);  // Refresh every minute


const rules = [
    {
        type: 'select',
        field: 'product',
        title: 'Select Product',
        effect: {
            loadData: {
                attr: 'inventoryOptions',
                to: 'options'
            }
        }
    }
];

Dynamically Load Data Based on Other Field Selection

In complex forms, after a user selects a field value, you may need to dynamically load data related to that selection. Use loadData combined with onChange events to achieve this logic.

js
// Initialize category data
formCreate.setData('categoryOptions', {
    electronics: [
        { label: 'Phone', value: 'phone' },
        { label: 'Computer', value: 'computer' }
    ],
    clothing: [
        { label: 'T-shirt', value: 'tshirt' },
        { label: 'Jeans', value: 'jeans' }
    ]
});


const rules = [
    {
        type: 'select',
        field: 'category',
        title: 'Select Category',
        options: [
            { label: 'Electronics', value: 'electronics' },
            { label: 'Clothing', value: 'clothing' }
        ],
        inject: true,
        on: {
            change(inject, val) {
                const products = inject.api.getData('categoryOptions')[val] || [];
                inject.api.getRule('products').options = products;
            }
        }
    },
    {
        type: 'select',
        field: 'products',
        title: 'Select Product',
        options: []
    }
];

The above demonstrates FormCreate's powerful functionality in handling complex dynamic form scenarios. Through flexible use of loadData, setData, onChange, and other methods, implement various complex business logic, making forms more intelligent and dynamic. Whether it's real-time validation, dependency handling, or dynamic data loading, FormCreate provides strong support.

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