Ant-design: Submit form from external button (Form in Modal)

Created on 20 Feb 2018  ·  8Comments  ·  Source: ant-design/ant-design

What problem does this feature solve?

I have a Model with a form in it and would like to submit the form with the button which is in the footer of the modal.
There's no such method like "submit".
The Only way I see right now is to give the form an ID and getit via getElementById and call submit().
But I would like to trigger the validation process too.
How can I achieve it?

What does the proposed API look like?

callable submit method on the form

Usage

Most helpful comment

@yesmeck Unfortunately handling submit via JS is not not enough and submit on enter still does not work.
Fortunately new form attribute solves the issue.

<Form id="myForm">...</>
...
<Button form="myForm" key="submit" htmlType="submit">
  Submit
</Button>

See browser support

All 8 comments

Hello @X-Tender, we use GitHub issues to trace bugs or discuss plans of Ant Design. So, please don't ask usage questions here. You can try to ask questions on Stack Overflow or Segment Fault, then apply tag antd and react to your question.

@yesmeck Unfortunately handling submit via JS is not not enough and submit on enter still does not work.
Fortunately new form attribute solves the issue.

<Form id="myForm">...</>
...
<Button form="myForm" key="submit" htmlType="submit">
  Submit
</Button>

See browser support

same request,any solutions?

I am just setting footer to null and put form inside the modal. It is very useful, when you want one form component for create and edit some entity.

How about:

 <Modal
        okButtonProps={{form:'category-editor-form', key: 'submit', htmlType: 'submit'}}
        onCancel={() => {
            dispatch({
                type: 'categoryEditor/closeEditor'
            })
        }}>
        <Form id='category-editor-form' layout="vertical" onFinish={onFinish}>

        </Form>

Why, guys, do you not like the hooks solution?

const [isOpen, setIsOpen] = useState(false);
const [form] = Form.useForm();

const onSubmit = useCallback((values) => {
// do your staff with values
}, []);

const closePopup = useCallback(() => {
  form.resetFields();
  setIsOpen(false);
}, [form]);

<Modal
  visible={isOpen}
  onOk={form.submit}
  onCancel={closePopup}
>
  <Form
    form={form}
    onFinish={onSubmit}
  />
</Modal>

@xr0master The hooks solution above works for many cases, but becomes cumbersome when you have several components between the Modal and the Form. You'll find yourself having to drill the props or use the context API.
It would be nice if there were a clean way to obtain a reference to any form on the page by using the form name or id.

Was this page helpful?
0 / 5 - 0 ratings