buttonreact-adminonerror

Custom save button that handles server side form validation


I'm on React Admin 4.2.4 and I have a custom save button where I would like it to detect the error from the API response and update the field in red as it does with normal form validation.

            <SaveButton
                variant="contained"
                id="createSave"
                alwaysEnable
                submitonenter="true"
                icon={<SaveIcon style={{ height: '20px', width: '20px' }} />}
                mutationOptions={{
                    onSuccess: (response) => {
                        refresh();
                        redirect('show', 'books', response.id);
                    },
                    onError: (error) => { notify(error.body.errors.username, {type: "error"}); }
                }}
                type="button"
            />

Everything works except getting the input field on the form to update with the red text. Is this doable? I haven't been able to find out how I can do this on this RA version


Solution

  • I solved this with the following:

     <SimpleForm onSubmit={save} 
    
    const save = useCallback(
            async values => {
                try {
                    await create('users', { data: values }, { returnPromise: true }).then(response => {
                        refresh();
                        redirect('show', 'users', response.id);
                    });
                } catch (error) {
                    if (error.body.errors) {
                        return error.body.errors;
                    }
                }
            },
            [create, redirect, refresh]
        );
    

    The trick was I couldn't have my custom save button as type "button", but I needed to redirect after submission.