During the form development process, there are occasional needs for combining attributes. The UI display fields are different from the backend data structure fields. For example, when interfacing with the backend, the province and city fields are often defined as two separate fields { province: Beijing, city: Haidian }, rather than a combined one { province: [Beijing, Haidian] }. Therefore, it is necessary to handle the values in initialValues and onFinish as follows:
importReactfrom'react';
import{Cascader,Form}from'antd';
const data ={ province:'Beijing', city:'Haidian'};
When the form is relatively simple, it's manageable, but when encountering a Form.List scenario, it becomes necessary to process the values using map, which can become quite complex. Therefore, we need to encapsulate an aggregated field component to enable a single Form.Item to handle multiple name attributes.
Approach Summary
To implement the aggregation field functionality, we need to utilize getValueProps, getValueFromEvent, and transform to facilitate the transformation of data from FormStore and to re-insert the structure into FormStore upon change.
getValueProps
By default, Form.Item passes the field value from FormStore as the value prop to the child component. However, with getValueProps, you can customize the props that are passed to the child component to implement transformation functionality. In an aggregation scenario, we can iterate through names and combine the values from FormStore into a single value that is then passed to the child component:
When the child component modifies the value, the setFields method is used to set the aggregated value returned by the child component to the corresponding name, thereby updating the values of names in FormStore:
In rules, the default provided value for validation originates from the value passed to the corresponding name when the child component changes. Additionally, it is necessary to retrieve the values of names from FormStore and use the transform method to modify the value of rules:
By doing so, we have implemented a feature that allows for operating multiple names within a Form.Item, making the form logic clearer and easier to maintain.
In addition to the Cascader example in the text, it is also applicable to components such as DatePicker.RangePicker. In other words, this method can be used in any scenario that requires the aggregation of multiple fields.
Additionally, there are some edge cases in this example that have not been considered. For instance, setFields([{ name:'city', value:'nanjing' }]) will not update the selected value of Cascader. To achieve a refresh effect, you need to add Form.useWatch(values => resetNames.map(name => get(values, name)), form);.
Feel free to explore more edge cases and handle them as needed.