ldc-laravel-base-project/resources/ts/back/Components/DynamicPages/DynamicWrapperModelSelect.tsx
2026-07-09 17:32:17 +02:00

65 lines
1.8 KiB
TypeScript

import { useEffect, useRef } from "react";
import { ModelSelect } from "@/back/Components/Inputs/ModelSelect";
import type { ConfigField } from "@/back/types/dynamic-pages";
import {
extractExcludedIdFromExists,
extractRequiredValidation,
extractTableFromExists,
} from "@/hooks/use-laravel-validation";
interface DynamicWrapperModelSelectProps {
field: ConfigField;
fieldName: string;
fieldValue: string | number | boolean | File | Date;
setData: (
name: string,
value: string | number | boolean | File | object | null,
) => void;
getTrans: (fieldLabel: string) => string;
}
export default function DynamicWrapperModelSelect({
field,
fieldName,
fieldValue,
setData,
getTrans,
}: DynamicWrapperModelSelectProps) {
// Extract only the model name from the validation.
const targetModel =
extractTableFromExists(field.validation) ?? "dynamic_pages";
// Add a custom prefix in the last part of the name.
const newName = fieldName.replace(/([^.\s]+)$/, "reserved_$1");
// Set a state at false.
const initializedRef = useRef(false);
// Set the model name in the custom key only once.
useEffect(() => {
if (initializedRef.current) return;
initializedRef.current = true;
// If the value isn't already present in content.
setData(newName, targetModel);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [newName, targetModel]);
return (
<ModelSelect
name={fieldName}
multiple={false}
closeOnSelect
responsive
targetModel={targetModel}
label={getTrans(field.label)}
exclude={extractExcludedIdFromExists(field.validation)}
placeholder="ex: John Doe"
defaultValues={fieldValue ? [Number(fieldValue)] : []}
required={extractRequiredValidation(field.validation)}
setData={setData}
/>
);
}