How to input and create two (or more than two) fields using React-Admin?

Viewed 79

The following code provided in React-Admin docs lets me pick a record and enter only ONE field into the database:

const choices = [
   { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
   { id: 456, first_name: 'Jane', last_name: 'Austen' },
];
const optionRenderer = choice => `${choice.first_name} ${choice.last_name}`;
<AutocompleteInput source="author_id" choices={choices} optionText={optionRenderer} optionValue = "first_name" />

So in this case, a field called "first_name" would be inserted into my database table.

Is there a way to enter all three fields as an input? For example, I would want 3 separate fields

id: 456, 
first_name: 'Jane', 
last_name: 'Austen'  

to be inserted into the database(not as a dictionary of 3 fields but 3 independent fields).

1 Answers

<AutocompleteInput> allows to select an existing record related to the current one (e.g. choosing the author for a post).

I understand that you want to create a new record instead. You can do so via the onCreate prop, as explained in the doc:

import { AutocompleteInput, Create, SimpleForm, TextInput } from 'react-admin';

const PostCreate = () => {
    const categories = [
        { name: 'Tech', id: 'tech' },
        { name: 'Lifestyle', id: 'lifestyle' },
    ];
    return (
        <Create>
            <SimpleForm>
                <TextInput source="title" />
                <AutocompleteInput
                    onCreate={(filter) => {
                        const newCategoryName = window.prompt('Enter a new category', filter);
                        const newCategory = { id: categories.length + 1, name: newCategoryName };
                        categories.push(newCategory);
                        return newCategory;
                    }}
                    source="category"
                    choices={categories}
                />
            </SimpleForm>
        </Create>
    );
}
Related