enumOptions and enum reader

This commit is contained in:
2026-06-04 03:37:44 +05:30
parent 2dbe9a5270
commit 7c33bd9c7c
8 changed files with 109 additions and 29 deletions

View File

@@ -12,6 +12,7 @@ import {
Divider,
} from '@mui/material';
import { ResourceField } from '../../types/config';
import { getFieldOptions } from '../../utils/options';
import ImageUploadField from './ImageUploadField';
interface FormFieldProps {
@@ -73,40 +74,40 @@ export default function FormField({
if (field.relation && relationDataMap[field.relation]) {
const relationData = relationDataMap[field.relation].data;
const isArrayRelation = field.type === 'array';
// Determine how to display the related item
const getOptionLabel = (option: any) => {
if (!option) return "";
if (field.displayField && option[field.displayField]) return option[field.displayField];
// Standard naming fields
return option.name || option.title || option.label || option.id || JSON.stringify(option);
};
const options = getFieldOptions(field, relationData);
const keyField = field.enumOption?.key ?? 'id';
const getOptionValue = (option: any) => {
// Return the whole object to maintain identity
return option;
};
// Normalize value: API returns whole objects on GET, but form uses key strings
const normalizedValue = (() => {
if (isArrayRelation && Array.isArray(value)) {
return value.map((v: any) => (v != null && typeof v === 'object' ? String(v[keyField] ?? '') : String(v)));
}
if (value != null && typeof value === 'object') {
return String(value[keyField] ?? '');
}
return value ?? (isArrayRelation ? [] : "");
})();
return (
<FormControl fullWidth>
<InputLabel shrink>{label}</InputLabel>
<Select
multiple={isArrayRelation}
value={value || (isArrayRelation ? [] : "")}
value={normalizedValue}
label={label}
displayEmpty
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
renderValue={(selected: any) => {
if (isArrayRelation) {
return (selected as any[]).map(getOptionLabel).join(', ');
return (selected as string[]).map(k => options.find(o => o.key === k)?.value ?? k).join(', ');
}
return getOptionLabel(selected);
return options.find(o => o.key === selected)?.value ?? selected;
}}
>
{relationData.map((option) => (
<MenuItem key={option.id || JSON.stringify(option)} value={getOptionValue(option)}>
{getOptionLabel(option)}
{options.map((opt) => (
<MenuItem key={opt.key} value={opt.key}>
{opt.value}
</MenuItem>
))}
</Select>
@@ -149,6 +150,7 @@ export default function FormField({
// 5. Enum Handling
if (field.type === 'enum' && field.options) {
const options = getFieldOptions(field);
return (
<FormControl fullWidth>
<InputLabel>{label}</InputLabel>
@@ -158,9 +160,9 @@ export default function FormField({
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
>
{field.options.map((opt: string) => (
<MenuItem key={opt} value={opt}>
{opt}
{options.map((opt) => (
<MenuItem key={opt.key} value={opt.key}>
{opt.value}
</MenuItem>
))}
</Select>