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

118 lines
2.6 KiB
TypeScript

import { z } from "zod/v4";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "~/components/custom_ui/form";
import { Button } from "~/components/ui/button";
import Input from "~/components/ui/input";
import { Switch } from "~/components/ui/switch";
import { useZodForm } from "~/lib/zodForm";
import type { Flags, FlagsId } from "~/schemas/public/Flags";
type FormProps = {
initialValues: Flags | null;
submitMutation: (values: Flags) => void;
handleRemove: (id: FlagsId) => void;
};
export const FormFlags = ({
initialValues,
submitMutation,
handleRemove,
}: FormProps) => {
const Schema = z.object({
id: z.string(),
value: z.boolean(),
});
type FormValues = z.infer<typeof Schema>;
let defaultValues: FormValues;
// This can come from your database or API.
if (!initialValues) {
defaultValues = {
id: "",
value: false,
};
} else {
defaultValues = {
id: initialValues.id,
value: initialValues.value,
};
}
z.config(z.locales.it());
const form = useZodForm(Schema, {
defaultValues: defaultValues,
});
function onSubmit(fields: FormValues) {
const values = {
id: fields.id as FlagsId,
value: fields.value,
};
submitMutation(values);
}
return (
<>
<Form {...form}>
<form
className="space-y-8 px-0.5"
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField
control={form.control}
name="id"
render={({ field }) => (
<FormItem>
<div className="flex flex-wrap items-center gap-x-2">
<FormLabel htmlFor="id">Codice</FormLabel>
<FormMessage />
</div>
<FormControl>
<Input placeholder="" {...field} id="id" />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="value"
render={({ field }) => (
<FormItem>
<div className="flex flex-wrap items-center gap-x-2">
<FormLabel htmlFor="value">Attivo/Inattivo</FormLabel>
<FormMessage />
</div>
<FormControl>
<Switch
className="data-[state=checked]:bg-neutral-700"
defaultChecked={field.value}
id="value"
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<div className="flex flex-row items-center justify-between">
<Button type="submit">Salva</Button>
{initialValues?.id && handleRemove && (
<Button
onClick={() => handleRemove(initialValues.id)}
type="button"
variant="destructive"
>
Cancella
</Button>
)}
</div>
</form>
</Form>
</>
);
};