skip to Main Content

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


  1. 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 salled details that responsible for handling your selected object. In there you can capture you id, firstName, and lastName.
    import React, { useState } from 'react';
    import TextField from '@mui/material/TextField';
    import Autocomplete from '@mui/material/Autocomplete';
    
    export default function ComboBox() {
      const [employee, setEmployee] = useState({
        id: 0,
        fullName: '',
      });
    
      const employees = [
        {
          id: 1,
          firstName: 'Hugo',
          lastName: 'Race'
        },
        {
          id: 2,
          firstName: 'Jack',
          lastName: 'Sheppard'
        },
        {
          id: 3,
          firstName: 'Kate',
          lastName: 'Ostin'
        },
      ];
    
      return (
        <Autocomplete
          disablePortal
          id="combo-box-demo"
          options={employees}
          sx={{ width: 300 }}
          value={employee.fullName}
          renderOption={(props, option, state) => {
            return (
              <div {...props}>
                <p>{option.firstName} {option.lastName}</p>
              </div>
            )
          }}
          renderInput={(params) => <TextField {...params} label="Employee" />}
          onChange={(event: React.SyntheticEvent, value: any, reason: string, details: any) => {
            setEmployee({
              ...employee,
              id: details?.option.id,
              fullName: `${details?.option.firstName} ${details?.option.lastName}`,
            });
          }}
        />
      );
    }
    
    Login or Signup to reply.
  2. The autocomplete component in MUI does not support the name attribute. You can do the following to achieve your goal.

        const employees: UserModel[] = [
          {
                id: 1,
                firstName: 'Hugo',
                lastName: 'Race'
              },
              {
                id: 2,
                firstName: 'Jack',
                lastName: 'Sheppard'
              },
              {
                id: 3,
                firstName: 'Kate',
                lastName: 'Ostin'
              },
            ];
        const [state, setState] = useState("");
    
        const handleChange = (event, value) => {
          setState({ studentId: value.id });
        };
            
            <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}
                onChange={handleChange}
                renderInput={(params) =>
                  <TextField
                    {...params}
                    label="Сотрудник"
                    variant="filled"
                    error={errors.studentId ? true : false}
                    {...register('studentId', {
                      required: errorLocales.validation.requiredField,
                    })}
                  />}
              />
            </Box>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search