Skip to main content
Version: 3.xx.xx

useModalForm

useModalForm hook allows you to manage a form within a modal. It returns Ant Design Form and Modal components props.

import { useModalForm } from "@pankod/refine-antd";

const { modalProps, formProps } = useModalForm<IPost>({
action: "create", // or "edit"
});

All we have to do is to pass the modalProps to <Modal> and formProps to <Form> components.

Usage​

We'll show two examples, one for creating and one for editing a post. Let's see how useModalForm is used in both.

Create Modal​

In this example, we will show you how to create a record with useModalForm.

pages/posts/list.tsx
import { useModalForm, Modal, Form, Create, Radio, List, Input } from "@pankod/refine-antd";

export const PostList: React.FC = () => {
const { modalProps, formProps, show } = useModalForm<IPost>({
action: "create",
});

return (
<>
<List
createButtonProps={{
onClick: () => {
show();
},
}}
>
...
</List>
<Modal {...modalProps}>
<Form {...formProps} layout="vertical">
<Form.Item label="Title" name="title">
<Input />
</Form.Item>
<Form.Item label="Status" name="status">
<Radio.Group>
<Radio value="draft">Draft</Radio>
<Radio value="published">Published</Radio>
<Radio value="rejected">Rejected</Radio>
</Radio.Group>
</Form.Item>
</Form>
</Modal>
</>
);
};

interface IPost {
id: number;
title: string;
status: "published" | "draft" | "rejected";
}

createButtonProps allows us to create and manage a button above the table.

    createButtonProps={{
onClick: () => {
show();
},
}}

This code block makes <Modal> appear when you click the button.

Create modal action

Edit Modal​

Let's learn how to add editing capabilities to records that will be opening form in Modal by using the action prop.

pages/posts/list.tsx
import {
useModalForm,
Modal,
Form,
Create,
Radio,
List,
Table,
EditButton,
Input
} from "@pankod/refine-antd";

export const PostList: React.FC = () => {
const {
modalProps,
formProps,
show,
id,
} = useModalForm<IPost>({
action: "edit",
});

return (
<>
<List>
<Table>
...
<Table.Column<IPost>
title="Actions"
dataIndex="actions"
key="actions"
render={(_value, record) => (
<EditButton onClick={() => show(record.id)} />
)}
/>
</Table>
</List>
<Modal {...modalProps}>
<Form {...formProps} layout="vertical">
<Form.Item label="Title" name="title">
<Input />
</Form.Item>
<Form.Item label="Status" name="status">
<Radio.Group>
<Radio value="draft">Draft</Radio>
<Radio value="published">Published</Radio>
<Radio value="rejected">Rejected</Radio>
</Radio.Group>
</Form.Item>
</Form>
</Modal>
</>
);
};

interface IPost {
id: number;
title: string;
status: "published" | "draft" | "rejected";
}

info

refine doesn't automatically add a edit button to the each record in <PostList> which opens edit form in <Modal> when clicked.

So, we have to put the edit buttons on our list. In that way, <Edit> form in <Modal> can fetch data by the record id.

<Table.Column<IPost>
title="Actions"
dataIndex="actions"
key="actions"
render={(_value, record) => <EditButton onClick={() => show(record.id)} />}
/>
caution

Don't forget to pass the record id to show to fetch the record data. This is necessary for both edit and clone forms.

Edit modal action

API Reference​

Properties​

KeyDescriptionTypeDefault
action
Required
Type of form mode"edit" | "create"| "clone""create"
idRecord id for fetchingBaseKeyId that it reads from the URL
autoSubmitCloseClose modal after submissionboolean
formAnt Design form instanceFormInstance<TVariables>
mutationModeDetermines when mutations are executed. If not explicitly configured, it is read from the mutation mode configuration of the resource in current route"pessimistic" | "optimistic" | "undoable"
onMutationErrorCalled when a mutation encounters an error(error: TError, variables: TVariables, context: any) => void
onMutationSuccessCalled when a mutation is successful(data: TData, variables: TVariables, context: any) => void
redirectPage to redirect after a succesfull mutation "show" | "edit" | "list" | "create" | false"list"
submitSubmit the form(values?: TVariables) => Promise<TData>
submitOnEnterListens Enter key press to submit formbooleanfalse
undoableTimeoutDuration to wait before executing mutations when mutationMode = "undoable"number5000*
warnWhenUnsavedChangesShows notification when unsaved changes existbooleanfalse*
successNotificationSuccessful Mutation notificationSuccessErrorNotification"Successfully created resource" or "Successfully updated resource"
errorNotificationUnsuccessful Mutation notificationSuccessErrorNotification"There was an error creating resource (status code: statusCode)" or "Error when updating resource (status code: statusCode)"
metaDataMetadata query for dataProviderMetaDataQuery{}
liveModeWhether to update data automatically ("auto") or not ("manual") if a related live event is received. The "off" value is used to avoid creating a subscription."auto" | "manual" | "off""off"
liveParamsParams to pass to liveProvider's subscribe method if liveMode is enabled.{ ids?: BaseKey[]; [key: string]: any; }undefined
onLiveEventCallback to handle all related live events of this hook.(event: LiveEvent) => voidundefined
invalidatesYou can use it to manage the invalidations that will occur at the end of the mutation.all, resourceAll, list, many, detail, false["list", "many", "detail"]
queryOptionsreact-query queryOptions of useOne hook used while in edit mode. UseQueryOptions<
{ data: TData[]; },
TError>

*: These props have default values in RefineContext and can also be set on <Refine> component. useModalForm will use what is passed to <Refine> as default but a local value will override it.

**: If not explicitly configured, default value of redirect depends on which action used. If action is create, redirects default value is edit (created resources edit page). If action is edit instead, redirects default value is list.

Return Value​

KeyDescriptionType
showA function that can open the modal(id?: BaseKey) => void
formPropsAnt Design form propsFormProps
modalPropsProps for managed modalModalProps
formLoadingLoading status of formboolean
submitSubmit method, the parameter is the value of the form fields() => void
visibleWhether the modal dialog is visible or notboolean
closeSpecify a function that can close the modal() => void
defaultFormValuesLoadingDefaultFormValues loading status of formboolean
formAnt Design form instanceFormInstance<TVariables>
idRecord id for edit actionBaseKey | undefined
setIdid setterDispatch<SetStateAction< BaseKey | undefined>>
queryResultResult of the query of a recordQueryObserverResult<{ data: TData }>
mutationResultResult of the mutation triggered by submitting the formUseMutationResult<
{ data: TData },
TError,
{ resource: string; values: TVariables; },
unknown>

Type Parameters​

PropertyDesriptionDefault
TDataResult data of the query that extends BaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpError
TVariablesValues for params.{}

Live StackBlitz Example​