When using Ant Design’s Modal
, you might encounter situations where you need to trigger the form's submission through the modal's onOk
button rather than the form's submit button. This can be achieved by programmatically calling the form's submit()
method. Here's a detailed guide on how to do this.
Scenario Overview:
Suppose you want the form to be submitted only after the user confirms the action in the modal by clicking the OK button, instead of directly submitting via a form button labeled Submit Request.
Solution: Use form.submit()
in the Modal onOk
Handler
To trigger the form’s submission programmatically, follow these steps:
- Move the submission logic into the
onFinish
function. - Remove the
htmlType="submit"
from the form's main button to prevent auto-submission. - Call
form.submit()
inside the modal'sonOk
handler to submit the form programmatically.
Simplified Code Example:
import React, { useState } from 'react';
import { Button, Form, Input, Modal } from 'antd';
const SimpleFormModal = () => {
const [form] = Form.useForm();
const [modalVisible, setModalVisible] = useState(false);
// Form submission logic
const onFinish = (values: any) => {
console.log('Form submitted with values:', values);
setModalVisible(false); // Close modal after submission
};
// Open modal
const showModal = () => {
setModalVisible(true);
};
// Programmatically submit form
const handleModalSubmit = () => {
form.submit();
};
return (
<div>
<Form form={form} layout="vertical" onFinish={onFinish}>
<Form.Item label="Name" name="name" rules={[{ required: true, message: 'Please enter your name' }]}>
<Input placeholder="Enter your name" />
</Form.Item>
<Button type="primary" onClick={showModal}>
Submit Request
</Button>
</Form>
<Modal
title="Confirm Submission"
open={modalVisible}
onOk={handleModalSubmit} // Trigger form submission when OK is clicked
onCancel={() => setModalVisible(false)}
okText="Confirm"
cancelText="Cancel"
>
<p>Are you sure you want to submit the form?</p>
</Modal>
</div>
);
};
export default SimpleFormModal;
Explanation:
showModal
function:
- Opens the modal when the Submit Request button is clicked.
2. handleModalSubmit
function:
- Calls
form.submit()
to programmatically trigger form submission when OK is pressed.
3. Modal onCancel
function:
- Closes the modal without submitting the form.
4. Form onFinish
function:
- Handles the form submission logic.
Result:
- When the user clicks Submit Request, the modal opens.
- After confirming by clicking Confirm, the form is submitted, and the modal closes.
- If the user clicks Cancel, the modal simply closes without submitting.
This approach enables you to create a more interactive and user-friendly form submission flow using Ant Design’s Modal
and Form
components.
Happy coding! ๐