infoalloggi-monorepo/apps/infoalloggi/src/forms/FormStringhe.tsx

126 lines
3.5 KiB
TypeScript
Raw Normal View History

2025-08-04 17:45:44 +02:00
import { z } from "zod";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "~/components/custom_ui/form";
import { customErrorMapWrapper } from "~/hooks/locale";
import { useZodForm } from "~/lib/zodForm";
import Input from "~/components/custom_ui/input";
import { Button } from "~/components/ui/button";
import type {
TestiEStringhe,
TestiEStringheStingaId,
} from "~/schemas/public/TestiEStringhe";
import Tiptap from "~/components/tip-tap/editor";
import { Confirm } from "~/components/confirm";
type FormProps = {
initialValues: TestiEStringhe | null;
submitMutation: (values: TestiEStringhe) => void;
del?: (stringheId: TestiEStringheStingaId) => void;
};
export const FormStringhe = ({
initialValues,
submitMutation,
del,
}: FormProps) => {
const Schema = z.object({
stinga_id: z.string(),
stringa_value: z.string().nullable(),
});
type FormValues = z.infer<typeof Schema>;
let defaultValues: FormValues;
// This can come from your database or API.
if (!initialValues) {
defaultValues = {
stinga_id: "",
stringa_value: null,
};
} else {
defaultValues = {
stinga_id: initialValues.stinga_id,
stringa_value: initialValues.stringa_value,
};
}
z.setErrorMap(customErrorMapWrapper("it"));
const form = useZodForm({
schema: Schema,
defaultValues: defaultValues,
});
function onSubmit(fields: FormValues) {
const values = {
stinga_id: fields.stinga_id as TestiEStringheStingaId,
stringa_value: fields.stringa_value,
};
submitMutation(values);
}
return (
<>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-8 px-0.5"
>
<FormField
control={form.control}
name="stinga_id"
render={({ field }) => (
<FormItem>
<div className="flex flex-wrap items-center gap-x-2">
<FormLabel htmlFor="stinga_id">Codice</FormLabel>
<FormMessage />
</div>
<FormControl>
<Input placeholder="" {...field} id="stinga_id" />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="stringa_value"
render={({ field }) => (
<FormItem>
<div className="flex flex-wrap items-center gap-x-2">
<FormLabel htmlFor="stringa_value">Valore testuale</FormLabel>
<FormMessage />
</div>
<FormControl>
<Tiptap
value={field.value || ""}
onChange={field.onChange}
id="stringa_value"
/>
</FormControl>
</FormItem>
)}
/>
<div className="flex flex-row items-center justify-between">
<Button type="submit" variant="success">
Salva
</Button>
{initialValues?.stinga_id && del && (
<Confirm
title="Cancellare la stringa?"
description="Questa azione è irreversibile"
onConfirm={() => del(initialValues.stinga_id)}
>
<Button variant="destructive">Cancella</Button>
</Confirm>
)}
</div>
</form>
</Form>
</>
);
};