You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
3.0 KiB
91 lines
3.0 KiB
import type { NextPage } from 'next';
|
|
import { MainLayout } from '../layout/MainLayout';
|
|
import { Input } from '../../components/Input';
|
|
import { useForm } from 'react-hook-form';
|
|
import { Button } from '../../components/Button';
|
|
import { useRouter } from 'next/router';
|
|
import { useEffect } from 'react';
|
|
import { Toolbar } from '../../components/Toolbar';
|
|
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth';
|
|
import { Manytoone } from '../../components/Manytoone';
|
|
import { saveWithAuth } from '../../hooks/saveWithAuth';
|
|
|
|
const ClientePage: NextPage = () => {
|
|
|
|
const router = useRouter();
|
|
const entityId: string = !!router.query.id ? router.query.id as string : "0";
|
|
const baseUrl = process.env.API_URL;
|
|
const { control, register, setValue,getValues,handleSubmit, formState: { isSubmitSuccessful, errors } } = useForm(
|
|
{
|
|
defaultValues: {
|
|
id: 0,
|
|
nombre: '',
|
|
telefono: '',
|
|
compania:0
|
|
}
|
|
}
|
|
);
|
|
|
|
const getInitData = async () => {
|
|
if (!entityId || entityId=="0")
|
|
return;
|
|
const { data, error } = await useFetchWithAuth("cliente/" + entityId);
|
|
|
|
if (!error) {
|
|
|
|
if (data.id!=0){
|
|
setValue("id", data['id'])
|
|
setValue("nombre", data['nombre'])
|
|
setValue("telefono", data['telefono'])
|
|
if (data['compania']){
|
|
setValue("compania", data['compania'].id)
|
|
}
|
|
}
|
|
|
|
} else {
|
|
console.log(error)
|
|
}
|
|
}
|
|
|
|
const onSubmit = async (entity: any) => {
|
|
try {
|
|
let endpoint = "cliente";
|
|
entity['compania'] = {id: entity['compania']}
|
|
const { data, error } = await saveWithAuth(endpoint, entityId, entity);
|
|
if (error) {
|
|
console.log(error);
|
|
} else {
|
|
router.push("/"+endpoint+"/form" + "?id=" + data.id)
|
|
}
|
|
} catch (e) {
|
|
console.log("Post error:");
|
|
console.table(e);
|
|
}
|
|
}
|
|
|
|
|
|
useEffect(() => {
|
|
getInitData();
|
|
}, [router.query.id])
|
|
|
|
return (
|
|
<>
|
|
<MainLayout title={'Compañia'} >
|
|
<Toolbar pathForm='/cliente/form' pathList='/cliente/' currentEntity={""} entityName='cliente'/>
|
|
<div className='h-96 w-4/6 mx-auto p-4 border-solid border-gray-300 border-2 rounded-xl '>
|
|
<form onSubmit={handleSubmit(onSubmit)}
|
|
>
|
|
<Input id='id' label='' register={register} type='hidden'/>
|
|
<Input id='nombre' label='Nombre' register={register} />
|
|
<Input id='telefono' label='Telefono' register={register} />
|
|
<Manytoone entity={ 'compania'} control={control} />
|
|
<Button type='submit' title='Guardar' />
|
|
{errors?.root?.server && <p>Form submit failed.</p>}
|
|
</form>
|
|
</div>
|
|
</MainLayout>
|
|
</>
|
|
)
|
|
}
|
|
|
|
export default ClientePage
|