karso/front/src/components/form/FormSelectMultiple.tsx

67 lines
1.9 KiB
TypeScript

import { RefObject } from 'react';
import { FormGroup } from '@/components/form/FormGroup';
import { UseFormidableReturn } from '@/components/form/Formidable';
import { SelectMultiple } from '@/components/select/SelectMultiple';
export type FormSelectMultipleProps = {
// Generic Form input
form: UseFormidableReturn;
// Form: Name of the variable
variableName: string;
// Forward object reference
ref?: RefObject<any>;
// Form: Label of the input
label?: string;
// Form: Placeholder if nothing is selected
placeholder?: string;
// Form: Specify if the element is required or not
isRequired?: boolean;
// List of object options
options: object[];
// in the option specify the value Key
keyInputKey?: string;
// in the option specify the value field
keyInputValue?: string;
// Add capability to add an item (no key but only value)
addNewItem?: (data: string) => Promise<any>;
};
export const FormSelectMultiple = ({
form,
variableName,
ref,
placeholder,
options,
keyInputKey = 'id',
keyInputValue = 'name',
addNewItem,
...rest
}: FormSelectMultipleProps) => {
// if set add capability to add the search item
const onCreate = !addNewItem
? undefined
: (data: string) => {
addNewItem(data).then((data: object) => form.setValues({ [variableName]: [...(form.values[variableName] ?? []), data[keyInputKey]] }));
};
return (
<FormGroup
enableModifyNotification={form.configuration.enableModifyNotification}
enableReset={form.configuration.enableReset}
isModify={form.isModify[variableName]}
onRestore={() => form.restoreValue({ [variableName]: true })}
{...rest}
>
<SelectMultiple
//ref={ref}
values={form.values[variableName]}
options={options}
onChange={(value) => form.setValues({ [variableName]: value })}
keyKey={keyInputKey}
keyValue={keyInputValue}
onCreate={onCreate}
/>
</FormGroup>
);
};