Raw
1 ---
2 sidebar_label: "Forms"
3 ---
4
5 import { Table } from "docs-ui"
6
7 export const metadata = {
8 title: `Forms - Admin Components`,
9 }
10
11 # {metadata.title}
12
13 In this guide, you'll learn how to create forms that match the Medusa Admin's design conventions.
14
15 The Medusa Admin has two types of forms:
16
17 1. Create forms, created using the [FocusModal UI component](!ui!/components/focus-modal).
18 2. Edit or update forms, created using the [Drawer UI component](!ui!/components/drawer).
19
20 This guide explains how to create these two form types following the Medusa Admin's conventions.
21
22 <Note>
23
24 These forms are built since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0) with the `Form` component that the `@medusajs/dashboard` package exports. Before that version, you had to compose the fields with `FormProvider` and `Controller` from react-hook-form yourself.
25
26 </Note>
27
28 ## Form Tooling
29
30 The Medusa Admin uses the following tools to build the forms:
31
32 1. The `Form` component from `@medusajs/dashboard/components`, which renders a field's label, control, hint, and error message with the Medusa Admin's styling.
33 2. [react-hook-form](https://react-hook-form.com/) to easily build forms and manage their states.
34 3. [Zod](https://zod.dev/) to validate the form's fields.
35
36 All of these are available in your project, so you don't have to install them to use them.
37
38 The `Form` component wraps react-hook-form's `FormProvider`, and has the following sub-components:
39
40 <Table>
41 <Table.Header>
42 <Table.Row>
43 <Table.HeaderCell>
44 Component
45 </Table.HeaderCell>
46 <Table.HeaderCell>
47 Description
48 </Table.HeaderCell>
49 </Table.Row>
50 </Table.Header>
51 <Table.Body>
52 <Table.Row>
53 <Table.Cell>
54
55 `Form.Field`
56
57 </Table.Cell>
58 <Table.Cell>
59
60 Registers a field in the form. It accepts the same props as react-hook-form's `Controller`.
61
62 </Table.Cell>
63 </Table.Row>
64 <Table.Row>
65 <Table.Cell>
66
67 `Form.Item`
68
69 </Table.Cell>
70 <Table.Cell>
71
72 Wraps a field's label, control, hint, and error message.
73
74 </Table.Cell>
75 </Table.Row>
76 <Table.Row>
77 <Table.Cell>
78
79 `Form.Label`
80
81 </Table.Cell>
82 <Table.Cell>
83
84 Shows the field's label. It accepts an `optional` prop to mark the field as optional, and `tooltip` and `icon` props.
85
86 </Table.Cell>
87 </Table.Row>
88 <Table.Row>
89 <Table.Cell>
90
91 `Form.Control`
92
93 </Table.Cell>
94 <Table.Cell>
95
96 Wraps the field's input and connects it to the form's accessibility and error state.
97
98 </Table.Cell>
99 </Table.Row>
100 <Table.Row>
101 <Table.Cell>
102
103 `Form.Hint`
104
105 </Table.Cell>
106 <Table.Cell>
107
108 Shows a hint below the field.
109
110 </Table.Cell>
111 </Table.Row>
112 <Table.Row>
113 <Table.Cell>
114
115 `Form.ErrorMessage`
116
117 </Table.Cell>
118 <Table.Cell>
119
120 Shows the field's validation error, if any.
121
122 </Table.Cell>
123 </Table.Row>
124 </Table.Body>
125 </Table>
126
127 ---
128
129 ## Create Form
130
131 In this section, you'll build a form component to create an item of a resource.
132
133 <Details summaryContent="Full Component">
134
135 ```tsx title="src/admin/components/create-form.tsx"
136 import {
137 FocusModal,
138 Heading,
139 Input,
140 Button,
141 } from "@medusajs/ui"
142 import { Form } from "@medusajs/dashboard/components"
143 import { useForm } from "react-hook-form"
144 import * as zod from "zod"
145
146 const schema = zod.object({
147 name: zod.string(),
148 })
149
150 export const CreateForm = () => {
151 const form = useForm<zod.infer<typeof schema>>({
152 defaultValues: {
153 name: "",
154 },
155 })
156
157 const handleSubmit = form.handleSubmit(({ name }) => {
158 // TODO: submit to backend
159 console.log(name)
160 })
161
162 return (
163 <FocusModal>
164 <FocusModal.Trigger asChild>
165 <Button>Create</Button>
166 </FocusModal.Trigger>
167 <FocusModal.Content>
168 <Form {...form}>
169 <form
170 onSubmit={handleSubmit}
171 className="flex h-full flex-col overflow-hidden"
172 >
173 <FocusModal.Header>
174 <div className="flex items-center justify-end gap-x-2">
175 <FocusModal.Close asChild>
176 <Button size="small" variant="secondary">
177 Cancel
178 </Button>
179 </FocusModal.Close>
180 <Button type="submit" size="small">
181 Save
182 </Button>
183 </div>
184 </FocusModal.Header>
185 <FocusModal.Body>
186 <div className="flex flex-1 flex-col items-center overflow-y-auto">
187 <div className="mx-auto flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
188 <div>
189 <Heading className="capitalize">
190 Create Item
191 </Heading>
192 </div>
193 <div className="grid grid-cols-2 gap-4">
194 <Form.Field
195 control={form.control}
196 name="name"
197 render={({ field }) => (
198 <Form.Item>
199 <Form.Label>Name</Form.Label>
200 <Form.Control>
201 <Input {...field} />
202 </Form.Control>
203 <Form.ErrorMessage />
204 </Form.Item>
205 )}
206 />
207 </div>
208 </div>
209 </div>
210 </FocusModal.Body>
211 </form>
212 </Form>
213 </FocusModal.Content>
214 </FocusModal>
215 )
216 }
217 ```
218
219 </Details>
220
221 Unlike other components in this documentation, this form component isn't reusable. You have to create one for every resource that has a create form in the admin.
222
223 Start by creating the file `src/admin/components/create-form.tsx` in which you'll create the form.
224
225 ### Create Validation Schema
226
227 In `src/admin/components/create-form.tsx`, create a validation schema with Zod for the form's fields:
228
229 ```tsx title="src/admin/components/create-form.tsx"
230 import * as zod from "zod"
231
232 const schema = zod.object({
233 name: zod.string(),
234 })
235 ```
236
237 The form in this guide is simple, it only has a required `name` field, which is a string.
238
239 ### Initialize Form
240
241 Next, you'll initialize the form using `react-hook-form`.
242
243 Add to `src/admin/components/create-form.tsx` the following:
244
245 ```tsx title="src/admin/components/create-form.tsx"
246 // other imports...
247 import { useForm } from "react-hook-form"
248
249 // validation schema...
250
251 export const CreateForm = () => {
252 const form = useForm<zod.infer<typeof schema>>({
253 defaultValues: {
254 name: "",
255 },
256 })
257
258 const handleSubmit = form.handleSubmit(({ name }) => {
259 // TODO: submit to backend
260 console.log(name)
261 })
262
263 // TODO render form
264 }
265 ```
266
267 You create the `CreateForm` component. For now, it uses `useForm` from `react-hook-form` to initialize a form.
268
269 You also define a `handleSubmit` function to perform an action when the form is submitted.
270
271 You can replace the content of the function with sending a request to Medusa's routes. Refer to [this guide](!docs!/learn/fundamentals/admin/tips#send-requests-to-api-routes) for more details on how to do that.
272
273 ### Render Components
274
275 You'll now add a `return` statement that renders the focus modal where the form is shown.
276
277 Replace `// TODO render form` with the following:
278
279 ```tsx title="src/admin/components/create-form.tsx"
280 // other imports...
281 import {
282 FocusModal,
283 Heading,
284 Input,
285 Button,
286 } from "@medusajs/ui"
287 import { Form } from "@medusajs/dashboard/components"
288
289 export const CreateForm = () => {
290 // ...
291
292 return (
293 <FocusModal>
294 <FocusModal.Trigger asChild>
295 <Button>Create</Button>
296 </FocusModal.Trigger>
297 <FocusModal.Content>
298 <Form {...form}>
299 <form
300 onSubmit={handleSubmit}
301 className="flex h-full flex-col overflow-hidden"
302 >
303 <FocusModal.Header>
304 <div className="flex items-center justify-end gap-x-2">
305 <FocusModal.Close asChild>
306 <Button size="small" variant="secondary">
307 Cancel
308 </Button>
309 </FocusModal.Close>
310 <Button type="submit" size="small">
311 Save
312 </Button>
313 </div>
314 </FocusModal.Header>
315 <FocusModal.Body>
316 <div className="flex flex-1 flex-col items-center overflow-y-auto">
317 <div className="mx-auto flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
318 <div>
319 <Heading className="capitalize">
320 Create Item
321 </Heading>
322 </div>
323 <div className="grid grid-cols-2 gap-4">
324 <Form.Field
325 control={form.control}
326 name="name"
327 render={({ field }) => (
328 <Form.Item>
329 <Form.Label>Name</Form.Label>
330 <Form.Control>
331 <Input {...field} />
332 </Form.Control>
333 <Form.ErrorMessage />
334 </Form.Item>
335 )}
336 />
337 </div>
338 </div>
339 </div>
340 </FocusModal.Body>
341 </form>
342 </Form>
343 </FocusModal.Content>
344 </FocusModal>
345 )
346 }
347 ```
348
349 You render a focus modal, with a trigger button to open it.
350
351 In the `FocusModal.Content` component, you wrap the content with the `Form` component, spreading into it the form you initialized earlier. `Form` provides the form's state to every field below it.
352
353 In the `Form` component, you add a `form` element passing it the `handleSubmit` function you created earlier as the handler of the `onSubmit` event.
354
355 In the `FocusModal.Header` component, you add buttons to save or cancel the form submission.
356
357 Finally, you render the form's fields inside the `FocusModal.Body`. Each field is a `Form.Field` component, which accepts the form's `control`, the field's `name`, and a `render` function.
358
359 In the `render` function, you wrap the field in a `Form.Item` component, then add:
360
361 - A `Form.Label` component showing the field's label.
362 - A `Form.Control` component wrapping the input, which connects the input to the form's accessibility and error state.
363 - A `Form.ErrorMessage` component showing the field's validation error, if any.
364
365 Since `Form.ErrorMessage` shows the errors of your Zod schema, you don't have to render validation messages yourself.
366
367 ### Use Create Form Component
368
369 You can use the `CreateForm` component in your widget or UI route.
370
371 For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
372
373 ```tsx title="src/admin/widgets/product-widget.tsx"
374 import { defineWidgetConfig } from "@medusajs/admin-sdk"
375 import { CreateForm } from "../components/create-form"
376 import { Container } from "../components/container"
377 import { Header } from "../components/header"
378
379 const ProductWidget = () => {
380 return (
381 <Container>
382 <Header
383 title="Items"
384 actions={[
385 {
386 type: "custom",
387 children: <CreateForm />,
388 },
389 ]}
390 />
391 </Container>
392 )
393 }
394
395 export const config = defineWidgetConfig({
396 zone: "product.details",
397 })
398
399 export default ProductWidget
400 ```
401
402 This component uses the [Container](../../guides/container/page.mdx) and [Header](../../guides/header/page.mdx) custom components.
403
404 It will add at the top of a product's details page a new section, and in its header you'll find a Create button. If you click on it, it will open the focus modal with your form.
405
406 ---
407
408 ## Edit Form
409
410 In this section, you'll build a form component to edit an item of a resource.
411
412 <Details summaryContent="Full Component">
413
414 ```tsx title="src/admin/components/edit-form.tsx"
415 import {
416 Drawer,
417 Heading,
418 Input,
419 Button,
420 } from "@medusajs/ui"
421 import { Form } from "@medusajs/dashboard/components"
422 import { useForm } from "react-hook-form"
423 import * as zod from "zod"
424
425 const schema = zod.object({
426 name: zod.string(),
427 })
428
429 export const EditForm = () => {
430 const form = useForm<zod.infer<typeof schema>>({
431 defaultValues: {
432 name: "",
433 },
434 })
435
436 const handleSubmit = form.handleSubmit(({ name }) => {
437 // TODO: submit to backend
438 console.log(name)
439 })
440
441 return (
442 <Drawer>
443 <Drawer.Trigger asChild>
444 <Button>Edit Item</Button>
445 </Drawer.Trigger>
446 <Drawer.Content>
447 <Form {...form}>
448 <form
449 onSubmit={handleSubmit}
450 className="flex flex-1 flex-col overflow-hidden"
451 >
452 <Drawer.Header>
453 <Heading className="capitalize">
454 Edit Item
455 </Heading>
456 </Drawer.Header>
457 <Drawer.Body className="flex max-w-full flex-1 flex-col gap-y-8 overflow-y-auto">
458 <Form.Field
459 control={form.control}
460 name="name"
461 render={({ field }) => (
462 <Form.Item>
463 <Form.Label>Name</Form.Label>
464 <Form.Control>
465 <Input {...field} />
466 </Form.Control>
467 <Form.ErrorMessage />
468 </Form.Item>
469 )}
470 />
471 </Drawer.Body>
472 <Drawer.Footer>
473 <div className="flex items-center justify-end gap-x-2">
474 <Drawer.Close asChild>
475 <Button size="small" variant="secondary">
476 Cancel
477 </Button>
478 </Drawer.Close>
479 <Button size="small" type="submit">
480 Save
481 </Button>
482 </div>
483 </Drawer.Footer>
484 </form>
485 </Form>
486 </Drawer.Content>
487 </Drawer>
488 )
489 }
490 ```
491
492 </Details>
493
494 Unlike other components in this documentation, this form component isn't reusable. You have to create one for every resource that has an edit form in the admin.
495
496 Start by creating the file `src/admin/components/edit-form.tsx` in which you'll create the form.
497
498 ### Create Validation Schema
499
500 In `src/admin/components/edit-form.tsx`, create a validation schema with Zod for the form's fields:
501
502 ```tsx title="src/admin/components/edit-form.tsx"
503 import * as zod from "zod"
504
505 const schema = zod.object({
506 name: zod.string(),
507 })
508 ```
509
510 The form in this guide is simple, it only has a required `name` field, which is a string.
511
512 ### Initialize Form
513
514 Next, you'll initialize the form using `react-hook-form`.
515
516 Add to `src/admin/components/edit-form.tsx` the following:
517
518 ```tsx title="src/admin/components/edit-form.tsx"
519 // other imports...
520 import { useForm } from "react-hook-form"
521
522 // validation schema...
523
524 export const EditForm = () => {
525 const form = useForm<zod.infer<typeof schema>>({
526 defaultValues: {
527 name: "",
528 },
529 })
530
531 const handleSubmit = form.handleSubmit(({ name }) => {
532 // TODO: submit to backend
533 console.log(name)
534 })
535
536 // TODO render form
537 }
538 ```
539
540 You create the `EditForm` component. For now, it uses `useForm` from `react-hook-form` to initialize a form.
541
542 You also define a `handleSubmit` function to perform an action when the form is submitted.
543
544 You can replace the content of the function with sending a request to Medusa's routes. Refer to [this guide](!docs!/learn/fundamentals/admin/tips#send-requests-to-api-routes) for more details on how to do that.
545
546 ### Render Components
547
548 You'll now add a `return` statement that renders the drawer where the form is shown.
549
550 Replace `// TODO render form` with the following:
551
552 ```tsx title="src/admin/components/edit-form.tsx"
553 // other imports...
554 import {
555 Drawer,
556 Heading,
557 Input,
558 Button,
559 } from "@medusajs/ui"
560 import { Form } from "@medusajs/dashboard/components"
561
562 export const EditForm = () => {
563 // ...
564
565 return (
566 <Drawer>
567 <Drawer.Trigger asChild>
568 <Button>Edit Item</Button>
569 </Drawer.Trigger>
570 <Drawer.Content>
571 <Form {...form}>
572 <form
573 onSubmit={handleSubmit}
574 className="flex flex-1 flex-col overflow-hidden"
575 >
576 <Drawer.Header>
577 <Heading className="capitalize">
578 Edit Item
579 </Heading>
580 </Drawer.Header>
581 <Drawer.Body className="flex max-w-full flex-1 flex-col gap-y-8 overflow-y-auto">
582 <Form.Field
583 control={form.control}
584 name="name"
585 render={({ field }) => (
586 <Form.Item>
587 <Form.Label>Name</Form.Label>
588 <Form.Control>
589 <Input {...field} />
590 </Form.Control>
591 <Form.ErrorMessage />
592 </Form.Item>
593 )}
594 />
595 </Drawer.Body>
596 <Drawer.Footer>
597 <div className="flex items-center justify-end gap-x-2">
598 <Drawer.Close asChild>
599 <Button size="small" variant="secondary">
600 Cancel
601 </Button>
602 </Drawer.Close>
603 <Button size="small" type="submit">
604 Save
605 </Button>
606 </div>
607 </Drawer.Footer>
608 </form>
609 </Form>
610 </Drawer.Content>
611 </Drawer>
612 )
613 }
614 ```
615
616 You render a drawer, with a trigger button to open it.
617
618 In the `Drawer.Content` component, you wrap the content with the `Form` component, spreading into it the form you initialized earlier.
619
620 In the `Form` component, you add a `form` element passing it the `handleSubmit` function you created earlier as the handler of the `onSubmit` event.
621
622 You render the form's fields inside the `Drawer.Body`. Each field is a `Form.Field` component whose `render` function returns a `Form.Item` component holding the field's `Form.Label`, `Form.Control`, and `Form.ErrorMessage` components.
623
624 Finally, in the `Drawer.Footer` component, you add buttons to save or cancel the form submission.
625
626 ### Use Edit Form Component
627
628 You can use the `EditForm` component in your widget or UI route.
629
630 For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
631
632 ```tsx title="src/admin/widgets/product-widget.tsx"
633 import { defineWidgetConfig } from "@medusajs/admin-sdk"
634 import { Container } from "../components/container"
635 import { Header } from "../components/header"
636 import { EditForm } from "../components/edit-form"
637
638 const ProductWidget = () => {
639 return (
640 <Container>
641 <Header
642 title="Items"
643 actions={[
644 {
645 type: "custom",
646 children: <EditForm />,
647 },
648 ]}
649 />
650 </Container>
651 )
652 }
653
654 export const config = defineWidgetConfig({
655 zone: "product.details",
656 })
657
658 export default ProductWidget
659 ```
660
661 This component uses the [Container](../../guides/container/page.mdx) and [Header](../../guides/header/page.mdx) custom components.
662
663 It will add at the top of a product's details page a new section, and in its header you'll find an "Edit Item" button. If you click on it, it will open the drawer with your form.
664