Hello all!
I am working to build a MUI Autocomplete control which supports multiple selections. I have the control rendering successfully in within JSONForms, but I am having an issue with the initial data binding. When I attempt to pass in the pre-selected enum values, I am passed the raw value, but when it is binding it is evaluating against the options in the select list. I’ve tried mapping the items but cannot seem to get them to bind correctly. Any help would be appreciated. Below is my current control. I am hoping I am missing something simple! Thanks in advance.
import merge from 'lodash/merge';
import {
ControlProps,
OwnPropsOfEnum,
WithClassname,
EnumOption,
isDescriptionHidden,
} from '@jsonforms/core';
import { Autocomplete, FormHelperText, Hidden, TextField } from '@mui/material';
import { WithOptionLabel } from '@jsonforms/material-renderers/lib/mui-controls/MuiAutocomplete';
import { useFocus } from '@jsonforms/material-renderers';
export const MultiSelectEnumArray = (
props: ControlProps & OwnPropsOfEnum & WithClassname & WithOptionLabel
) => {
const [focused, onFocus, onBlur] = useFocus();
const {
description,
className,
config,
id,
label,
required,
errors,
data,
visible,
options,
handleChange,
path,
enabled,
getOptionLabel,
} = props;
const isValid = errors.length === 0;
const appliedUiSchemaOptions = merge({}, config, props.uischema.options);
const showDescription = !isDescriptionHidden(
visible,
description,
focused,
appliedUiSchemaOptions.showUnfocusedDescription
);
const firstFormHelperText = showDescription
? description
: !isValid
? errors
: null;
const secondFormHelperText = showDescription && !isValid ? errors : null;
const onChange = (_ev: any, value: EnumOption[]) => {
var values: EnumOption[] = [];
value.forEach((el) => {
values.push(el.value);
});
return handleChange(path, values);
};
return (
<Hidden xsUp={!visible}>
<Autocomplete
id={id}
multiple
className={className}
disabled={!enabled}
autoHighlight
autoSelect
autoComplete
fullWidth
getOptionLabel={getOptionLabel || ((option) => option?.label)}
freeSolo={false}
options={options ? options : []}
onChange={onChange}
renderInput={(params) => {
return (
<TextField
label={label}
variant={
appliedUiSchemaOptions.variant
? appliedUiSchemaOptions.variant
: 'outlined'
}
inputRef={params.InputProps.ref}
autoFocus={appliedUiSchemaOptions.focus}
{...params}
id={id + '-input'}
required={
required && !appliedUiSchemaOptions.hideRequiredAsterisk
}
error={!isValid}
fullWidth={!appliedUiSchemaOptions.trim}
InputLabelProps={data ? { shrink: true } : undefined}
onFocus={onFocus}
onBlur={onBlur}
focused={focused}
/>
);
}}
/>
<FormHelperText error={!isValid && !showDescription}>
{firstFormHelperText}
</FormHelperText>
<FormHelperText error={!isValid}>{secondFormHelperText}</FormHelperText>
</Hidden>
);
};