import { zodResolver } from "@hookform/resolvers/zod"; import Button from "../../components/Button/Button"; import { Grid } from "../../components/Grid/Grid"; import Textfield from "../../components/Textfeild/Textfeild"; import { useForm, Controller } from "react-hook-form"; import { zValidateEnglishString, zValidateNumber, } from "../../data/getFormTypeErrors"; import { z } from "zod"; import { useApiMutation } from "../../utils/useApiRequest"; import { useToast } from "../../hooks/useToast"; import { useModalStore } from "../../context/zustand-store/appStore"; import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete"; const schema = z.object({ page: zValidateEnglishString("نام صفحه"), domain: zValidateNumber("حوزه"), }); type AddPageProps = { getData: () => void; item?: any; }; type FormValues = z.infer; export const AddPage = ({ getData, item }: AddPageProps) => { const showToast = useToast(); const { closeModal } = useModalStore(); const { control, handleSubmit, setValue, formState: { errors }, } = useForm({ resolver: zodResolver(schema), defaultValues: { page: item?.name || "", domain: item?.domain?.id, }, }); const mutation = useApiMutation({ api: `/auth/api/v1/page/${item ? item?.id + "/" : ""}`, method: item ? "put" : "post", }); const onSubmit = async (data: FormValues) => { try { const payload = { name: data.page, code: data.page + ".view", domain: data.domain, }; if (item) { await mutation.mutateAsync({ ...payload, id: item.id, }); } else { await mutation.mutateAsync(payload); } showToast("عملیات با موفقیت انجام شد", "success"); closeModal(); getData(); } catch (error: any) { if (error.status === 400) { showToast("این صفحه تکراری است!", "error"); } } }; return (
( )} /> ( { setValue("domain", value); }} /> )} />
); };