You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在react-admin中基于Edit与SimpleForm创建自定义提交表单

Custom Form with Custom Submission Actions & Types in react-admin

Let's walk through practical approaches to customize your form's submission behavior while working with the <Edit> and <SimpleForm> components you're already using.

1. Override Default Submission Logic with onSubmit

The most straightforward way to take control of submission is passing an onSubmit prop to <SimpleForm>. This lets you tweak data before sending, use custom request methods, or even call entirely separate endpoints.

Here's how to adapt your CategoryEdit component:

import { useDataProvider, useNotify, useRedirect } from 'react-admin';
import { Edit, SimpleForm, DisabledInput, TextInput } from 'react-admin';

const CategoryEdit = (props) => {
  const dataProvider = useDataProvider();
  const notify = useNotify();
  const redirect = useRedirect();

  // Custom submit handler with full control
  const handleCustomSubmit = async (values) => {
    try {
      // Modify form values if needed (e.g., add timestamps, transform fields)
      const modifiedValues = { ...values, lastUpdated: new Date().toISOString() };

      // Customize the request: switch from default PATCH to PUT, or adjust data
      await dataProvider.update('category', {
        id: values.id,
        data: modifiedValues,
      });

      notify('Category updated successfully!');
      redirect('/category'); // Redirect to list page after success
    } catch (error) {
      notify('Failed to update category', { type: 'error' });
    }
  };

  return (
    <Edit actions={<CategoryEditActions />} title={<CategoryTitle />} {...props}>
      <SimpleForm onSubmit={handleCustomSubmit}>
        <DisabledInput source="id" />
        <DisabledInput source="code" />
        <TextInput source="name" />
      </SimpleForm>
    </Edit>
  );
};

export default CategoryEdit;

Note: React-admin uses PATCH for Edit forms by default. If you need PUT or another method, most built-in data providers support overriding this—just check your data provider's documentation if you're using a custom one.

2. Custom Submit Buttons for Multiple Actions

If you need extra submission options (like "Save & Publish" or "Save & Stay"), replace the default submit button with a custom component using the submitButton prop.

First, create your custom button component:

import { Button, useFormContext, useDataProvider, useNotify, useRedirect } from 'react-admin';

const CustomSubmitButtons = () => {
  const { handleSubmit } = useFormContext();
  const dataProvider = useDataProvider();
  const notify = useNotify();
  const redirect = useRedirect();

  const handleSaveAndPublish = async () => {
    await handleSubmit((values) => 
      dataProvider.update('category', {
        id: values.id,
        data: { ...values, status: 'published' }
      })
    )();
    notify('Category published successfully!');
    redirect('/category');
  };

  return (
    <div style={{ display: 'flex', gap: '10px' }}>
      <Button type="submit" variant="contained" color="primary">
        Save
      </Button>
      <Button 
        onClick={handleSaveAndPublish} 
        variant="contained" 
        color="secondary"
      >
        Save & Publish
      </Button>
    </div>
  );
};

Then use it in your form:

<SimpleForm submitButton={<CustomSubmitButtons />}>
  <DisabledInput source="id" />
  <DisabledInput source="code" />
  <TextInput source="name" />
</SimpleForm>

3. Full Custom Form with <Form> Component (Maximum Flexibility)

For complete control over layout, conditional fields, or custom API calls, replace <SimpleForm> with react-admin's lower-level <Form> component. This lets you build the form exactly how you want.

Example implementation:

import { Edit, Form, DisabledInput, TextInput, Button, useNotify, useRedirect } from 'react-admin';

const CategoryEdit = (props) => {
  const notify = useNotify();
  const redirect = useRedirect();
  const record = props.record;

  const handleCustomSubmit = async (values) => {
    try {
      // Directly call a custom endpoint instead of using dataProvider
      await fetch(`/custom-category-api/${values.id}`, {
        method: 'POST', // Use any request type you need
        headers: {
          'Content-Type': 'application/json',
          // Add auth headers if required
        },
        body: JSON.stringify(values)
      });

      notify('Category updated via custom endpoint!');
      redirect('/category');
    } catch (error) {
      notify('Submission failed', { type: 'error' });
    }
  };

  return (
    <Edit actions={<CategoryEditActions />} title={<CategoryTitle />} {...props}>
      <Form initialValues={record} onSubmit={handleCustomSubmit}>
        <DisabledInput source="id" />
        <DisabledInput source="code" />
        <TextInput source="name" />
        <Button type="submit" variant="contained" color="primary" style={{ marginTop: '16px' }}>
          Submit Custom
        </Button>
      </Form>
    </Edit>
  );
};

Quick Tips:

  • When overriding onSubmit, you lose react-admin's default error handling, so be sure to add your own with useNotify and useRedirect.
  • Use the useFormContext hook to access form state (values, errors, touched fields) in any component inside the form.
  • If you need to modify request URLs globally for a resource, customize your data provider—but the methods above are better for page-specific changes.

内容的提问来源于stack exchange,提问作者Chetan Gawai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:22:04