field-form
field-form copied to clipboard
Why no onFieldsChange in FormInstance?
It is very limiting to have onFieldsChange only on <Form> instead of on FormInstance. I would like to be able to add a listener to form so other components can react to fields changing.
My current use case is automatically disabling the buttons in <Modal> if no fields are dirty:
/**
* Don't want to repeat logic over and over, want one Modal component that automatically
* changes ok/cancel buttons based on form state
*/
function MyFormModal() {
const [form] = Form.useForm()
return (
<Modal form={form} visible>
<Form form={form}>
...
</Form>
</Modal>
)
}
// disable okButton if dirty
// only show cancelButton if dirty
const Modal = ({form, onFinish, ...props}) => {
const [dirty, setDirty] = useState(false)
if(form) {
// Really need this!!
form.onFieldsChange(() => {
setDirty(form.isFieldTouched())
})
}
const buttonsProps = {
cancelButtonProps: dirty ? cancelButtonProps : {...cancelButtonProps, style: {display: 'none'}},
okButtonProps: dirty ? okButtonProps : {...okButtonProps, disabled: true}
}
return <AntModal {buttonsProps} {...props}/>
}
How can I achieve this currently?
Is this a bad idea?
form.getInternalHooks('RC_FORM_INTERNAL_HOOKS').setCallbacks({
onValuesChange: (values) => {
setDirty(form.isFieldTouched())
}
})