I have a component that needs to display names in the options list, but at the same time send the name ID in the form. How can this be done?
const employees: UserModel[] = [
{
id: 1,
firstName: 'Hugo',
lastName: 'Race'
},
{
id: 2,
firstName: 'Jack',
lastName: 'Sheppard'
},
{
id: 3,
firstName: 'Kate',
lastName: 'Ostin'
},
];
<Box
component="form"
id="applicationForm"
noValidate
>
<Autocomplete
options={employees}
getOptionLabel={(option: UserModel) => (`${option.firstName} ${option.lastName}`)}
getOptionKey={(option: UserModel) => option.id}
id="studentId"
isOptionEqualToValue={(option, value) => option.id === value.id}
renderInput={(params) =>
<TextField
{...params}
label="Сотрудник"
variant="filled"
error={errors.studentId ? true : false}
{...register('studentId', {
required: errorLocales.validation.requiredField,
})}
/>}
/>
</Box>
Now when sending a form the full name is sent, but you need to send the ID
2
Answers
You can obtain the result by following this
renderOption
– we can manupilate our object data in here. You can use tags inside it.option
prop is responsible for handling your object data.onChange
– There is a prop salleddetails
that responsible for handling your selected object. In there you can capture youid
,firstName
, andlastName
.The autocomplete component in MUI does not support the name attribute. You can do the following to achieve your goal.