Implemented extra fields for spools and vendors as well

This commit is contained in:
Donkie
2024-01-23 19:27:34 +01:00
parent fb23024ed0
commit 40d3a3184f
19 changed files with 287 additions and 125 deletions

View File

@@ -1,25 +1,52 @@
import React, { useState } from "react";
import { IResourceComponentsProps, useTranslate } from "@refinedev/core";
import { HttpError, IResourceComponentsProps, useTranslate } from "@refinedev/core";
import { Edit, useForm } from "@refinedev/antd";
import { Form, Input, DatePicker, message, Alert } from "antd";
import { Form, Input, DatePicker, message, Alert, Typography } from "antd";
import dayjs from "dayjs";
import TextArea from "antd/es/input/TextArea";
import { IVendor } from "./model";
import { IVendor, IVendorParsedExtras } from "./model";
import { EntityType, useGetFields } from "../../utils/queryFields";
import { ExtraFieldFormItem, StringifiedExtras } from "../../components/extraFields";
import { ParsedExtras } from "../../components/extraFields";
/*
The API returns the extra fields as JSON values, but we need to parse them into their real types
in order for Ant design's form to work properly. ParsedExtras does this for us.
We also need to stringify them again before sending them back to the API, which is done by overriding
the form's onFinish method. Form.Item's normalize should do this, but it doesn't seem to work.
*/
export const VendorEdit: React.FC<IResourceComponentsProps> = () => {
const t = useTranslate();
const [messageApi, contextHolder] = message.useMessage();
const [hasChanged, setHasChanged] = useState(false);
const extraFields = useGetFields(EntityType.vendor);
const { formProps, saveButtonProps } = useForm<IVendor>({
const { formProps, saveButtonProps } = useForm<IVendor, HttpError, IVendorParsedExtras, IVendorParsedExtras>({
liveMode: "manual",
onLiveEvent() {
// Warn the user if the vendor has been updated since the form was opened
messageApi.warning(t("vendor.form.vendor_updated"));
setHasChanged(true);
},
queryOptions: {
select(data) {
return {
data: ParsedExtras(data.data),
};
},
},
});
// Override the form's onFinish method to stringify the extra fields
const originalOnFinish = formProps.onFinish;
formProps.onFinish = (allValues: IVendorParsedExtras) => {
if (allValues !== undefined && allValues !== null) {
allValues = StringifiedExtras(allValues);
}
originalOnFinish?.(allValues);
};
return (
<Edit saveButtonProps={saveButtonProps}>
{contextHolder}
@@ -71,6 +98,10 @@ export const VendorEdit: React.FC<IResourceComponentsProps> = () => {
>
<TextArea maxLength={1024} />
</Form.Item>
<Typography.Title level={5}>{t("settings.extra_fields.tab")}</Typography.Title>
{extraFields.data?.map((field, index) => (
<ExtraFieldFormItem key={index} field={field} />
))}
</Form>
{hasChanged && <Alert description={t("vendor.form.vendor_updated")} type="warning" showIcon />}
</Edit>