Search code examples
javascriptreactjstypescriptreact-admin

Custom function to save a form using React Admin


In my react-admin app, I have a list of items accompanied by two buttons: Create using email and create. The "create" button is pre-existing and uses the funcionalitties by the data provider. However, when I opt for "create with email", a different form appears. For this form, I wish to execute a custom function rather the default one provided by the data provider. How can achieve this?

I searched in the documentation and stackoverflow, but couldn;t find anything relevant...


Solution

  • It’s not entirely clear what actions you want to take when saving, but here’s a similar example: https://marmelab.com/react-admin/SaveButton.html#onclick

    const MyToolbar = () => {
        const { getValues } = useFormContext();
        const redirect = useRedirect();
    
        const handleClick = e => {
            e.preventDefault(); // necessary to prevent default SaveButton submit logic
            const { id, ...data } = getValues();
            
    // Your steps to save form values...
            
            redirect('list');
        };
    
        return (
            <Toolbar>
                <SaveButton />        
                <SaveButton type="button" onClick={handleClick} />
            </Toolbar>
        );
    };
    
    export const MyCreate = () => (
        <Create>
            <SimpleForm toolbar={<MyToolbar/>}>
              ...
            </SimpleForm>
        </Create>
    );