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

如何在Admin-on-Rest创建表单中让SelectInput同时获取ID和Name值

解决Admin-on-Rest中SelectInput同时保存id和name到不同字段的问题

嘿,我来帮你搞定这个需求!在Admin-on-Rest里,默认的SelectInput只会把选中项的id赋值给指定的source字段,但要同时把对应的name存到category_name字段,我们可以借助FormDataConsumer组件来手动监听选择变化并更新表单数据。

方法一:直接在表单中使用FormDataConsumer包裹SelectInput

首先导入需要的组件,然后在你的表单里替换原来的SelectInput:

import { SelectInput, FormDataConsumer } from 'admin-on-rest';

// 嵌入到你的Edit或Create表单中
<FormDataConsumer>
    {({ formData, setFormData, ...rest }) => (
        <SelectInput
            source="category"
            choices={[
                { id: '1', name: 'Programming' },
                { id: '2', name: 'Lifestyle' },
                { id: '3', name: 'Photography' },
            ]}
            onChange={(event, newValue) => {
                // 根据选中的id找到对应的选项
                const selectedChoice = rest.choices.find(choice => choice.id === newValue);
                // 同时更新category和category_name两个字段
                setFormData({
                    ...formData,
                    category: newValue,
                    category_name: selectedChoice ? selectedChoice.name : ''
                });
            }}
            {...rest}
        />
    )}
</FormDataConsumer>

方法二:自定义可复用的SelectInput组件

如果这个需求在多个表单里都要用到,不如把逻辑封装成自定义组件,方便复用:

import { SelectInput, FormDataConsumer } from 'admin-on-rest';

const CategorySelectInput = ({ source, choices, ...rest }) => (
    <FormDataConsumer>
        {({ formData, setFormData }) => (
            <SelectInput
                source={source}
                choices={choices}
                onChange={(event, newValue) => {
                    const selectedChoice = choices.find(choice => choice.id === newValue);
                    setFormData({
                        ...formData,
                        [source]: newValue,
                        category_name: selectedChoice ? selectedChoice.name : ''
                    });
                }}
                {...rest}
            />
        )}
    </FormDataConsumer>
);

// 在表单中使用自定义组件
<CategorySelectInput 
    source="category" 
    choices={[
        { id: '1', name: 'Programming' },
        { id: '2', name: 'Lifestyle' },
        { id: '3', name: 'Photography' },
    ]} 
/>

关键说明

  • FormDataConsumer会提供当前表单的formData(现有表单数据)和setFormData(更新表单数据的方法),让我们能手动修改多个字段。
  • 在onChange事件中,我们通过选中的newValue(也就是选项的id)从choices数组里找到对应的name,然后一并更新两个字段。
  • 加了selectedChoice ? selectedChoice.name : ''的判断,是为了处理选中值为空的情况,避免出现undefined。

这样设置之后,当你选择分类时,表单里的category和category_name会同时被赋值,提交的时候就能一起传递这两个值啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:53:14