cherry-pick: Action中Required属性和Form校验合并 #4689 #4677 (#4697)

This commit is contained in:
RUNZE LU 2022-06-27 15:24:39 +08:00 committed by GitHub
parent a6fe86744a
commit 508677ca46
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 91 additions and 25 deletions

View File

@ -648,6 +648,77 @@ Access-Control-Expose-Headers: Content-Disposition
该 actionType 为[FormItem-Table](./form/input-table#按钮触发新增行)专用行为
### 校验表单
下面的表单中会优先校验按钮`required`属性包含的表单项,当所有的字段校验完毕后,才会校验表单中固有的项目。需要额外注意的是,当按钮中的 `required` 和对应表单项本身的 `required` 属性冲突时,最终校验方式是`"required": true`。
```schema: scope="body"
{
"type":"button",
"label":"打开弹窗表单",
"level": "primary",
"actionType":"dialog",
"dialog":{
"type":"dialog",
"title":"系统提示",
"closeOnEsc": true,
"body": [
{
"type":"form",
"title":"表单",
"api":"/api/mock2/form/saveForm",
"body":[
{
"label":"字段a",
"type":"input-text",
"name":"a",
"required":true
},
{
"name":"b",
"label":"字段b",
"type":"input-text",
"validations": {
"minimum": 1,
"isNumeric": true,
"isInt": true
},
"required": false
},
{
"name":"c",
"label":"字段c",
"type":"input-text"
},
{
"name":"d",
"label":"字段d",
"type":"input-text",
"required":true
}
]
}
],
"actions":[
{
"type":"submit",
"label":"提交-校验字段b",
"actionType":"submit",
"required":["b"],
"level": "info"
},
{
"type":"submit",
"label":"提交-校验字段b, c",
"actionType":"submit",
"required":["b", "c"],
"level": "info"
}
]
}
}
```
### 重置表单
在 form 中,配置`"type": "reset"`的按钮,可以实现重置表单数据的功能

View File

@ -922,13 +922,13 @@ export default class Form extends React.Component<FormProps, object> {
);
}
handleAction(
async handleAction(
e: React.UIEvent<any> | void,
action: ActionObject,
data: object,
throwErrors: boolean = false,
delegate?: IScopedContext
): any {
): Promise<any> {
const {
store,
onSubmit,
@ -967,13 +967,16 @@ export default class Form extends React.Component<FormProps, object> {
data = store.data;
}
if (Array.isArray(action.required) && action.required.length) {
/** 如果是按钮指定了required则校验前先清空一下遗留的校验报错 */
store.clearErrors();
const fields = action.required.map(item => ({
name: item,
rules: {isRequired: true}
}));
const validationRes = await store.validateFields(fields);
return store.validateFields(fields).then(async result => {
if (!result) {
if (!validationRes) {
const dispatcher = await dispatchEvent(
'validateError',
this.props.data
@ -985,17 +988,9 @@ export default class Form extends React.Component<FormProps, object> {
/** 抛异常是为了在dialog中catch这个错误避免弹窗直接关闭 */
return Promise.reject(__('Form.validateFailed'));
} else {
dispatchEvent('validateSucc', this.props.data);
this.handleAction(
e,
{...action, required: undefined},
data,
throwErrors,
delegate
);
/** 重置validated状态保证submit时触发表单中的校验项 */
store.clearErrors();
}
return;
});
}
if (
action.type === 'submit' ||