From dd2b62ed13d925793cf32a0219f63fba09fef2e0 Mon Sep 17 00:00:00 2001 From: Markus Thielker Date: Sat, 9 Mar 2024 18:02:54 +0100 Subject: [PATCH] N-FIN-5: add entity form schema and component --- src/components/form/entityForm.tsx | 102 +++++++++++++++++++++++ src/lib/form-schemas/entityFormSchema.ts | 8 ++ 2 files changed, 110 insertions(+) create mode 100644 src/components/form/entityForm.tsx create mode 100644 src/lib/form-schemas/entityFormSchema.ts diff --git a/src/components/form/entityForm.tsx b/src/components/form/entityForm.tsx new file mode 100644 index 0000000..85dbd8a --- /dev/null +++ b/src/components/form/entityForm.tsx @@ -0,0 +1,102 @@ +'use client'; + +import { zodResolver } from '@hookform/resolvers/zod'; +import { useForm } from 'react-hook-form'; +import { z } from 'zod'; +import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'; +import { Input } from '@/components/ui/input'; +import React from 'react'; +import { Button } from '@/components/ui/button'; +import { ActionResponse } from '@/lib/types/ActionResponse'; +import { useRouter } from 'next/navigation'; +import { toast } from 'sonner'; +import { sonnerContent } from '@/components/ui/sonner'; +import { entityFormSchema } from '@/lib/form-schemas/entityFormSchema'; +import { Entity, EntityType } from '@prisma/client'; +import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; + +export default function EntityForm({value, onSubmit, className}: { + value: Entity | undefined, + onSubmit: (data: z.infer) => Promise + className?: string +}) { + + const router = useRouter(); + + const form = useForm>({ + resolver: zodResolver(entityFormSchema), + defaultValues: { + id: value?.id ?? undefined, + name: value?.name ?? '', + type: value?.type ?? EntityType.Entity, + }, + }); + + const handleSubmit = async (data: z.infer) => { + const response = await onSubmit(data); + toast(sonnerContent(response)); + if (response.redirect) { + router.push(response.redirect); + } + }; + + return ( +
+ + + ( + + + + + + + )} + /> + +
+ ( + + Name + + + + + + )} + /> + ( + + Type + + + + )} + /> +
+ + + + ); +} diff --git a/src/lib/form-schemas/entityFormSchema.ts b/src/lib/form-schemas/entityFormSchema.ts new file mode 100644 index 0000000..b93b1d4 --- /dev/null +++ b/src/lib/form-schemas/entityFormSchema.ts @@ -0,0 +1,8 @@ +import { z } from 'zod'; +import { EntityType } from '@prisma/client'; + +export const entityFormSchema = z.object({ + id: z.number().positive().optional(), + name: z.string().min(3).max(32), + type: z.nativeEnum(EntityType), +});