简体   繁体   中英

Can I use ReferenceArrayInput to edit a list of objects (not just a list of IDs)?

In React-Admin I have an item I am trying to administer, it looks a bit like this:

{
  "title": "Title of my record",
  "source_id": "525560",
  "source_timestamp": 1547732039,
  "tags": [
    {
      "id": 9,
      "name": "Tag0",
      "description": "Descriptio of tag 0"
    },
    {
      "id": 10,
      "name": "Tag1",
      "description": "Descriptio of tag 1"
    }
  ]
}

The tags are given as a list of objects inside the main item.

I want to be able to admin this, but the code I have inside my Edit view is wrong:

export const IncidentEdit = props => {
    var _tag_ids = [1,2,3,4];
    return <Edit title={<IncidentTitle/>} {...props}>
        <SimpleForm>
            <TextInput fullWidth source="title"/>
            <TextField source="description"/>

            <ReferenceArrayInput label="tags" reference="tag" source="tags">
                <SelectArrayInput>
                    <ChipField source="name"/>
                </SelectArrayInput>
            </ReferenceArrayInput>

        </SimpleForm>
    </Edit>
};

This does not work because ReferenceArrayInput expects record.tags to be a list of tag foreign keys. Its actually a list of tags (so we don't actually have to look anything up). It also fails, because what it returns is a list of foreign keys - whereas the API is just expecting a list of tag objects back.

We might argue that the API is badly designed, but can React Admin accommodate this?

Is there a way for me to translate these records into list of forign-key IDs before I feed them into ReferenceArrayInput and then do the reverse before I send them back to the API? Alternativly, I could just change the APIs so that it only returns the foreign-keys and not the actual tag objects.

In this case seems like you don't have to fetch additional data. Your API response is ok, maybe only the aproach is not the right one.

Why not using the ArrayInput with SimpleIterator ? It allows you to edit all the fields inside the nested records and even use ReferenceInputs if needed.

<ArrayInput source="tags">
    <SimpleFormIterator>
        <TextInput source="id" disabled />
        <TextInput source="name" />
        <TextInput source="description" />
    </SimpleFormIterator>
</ArrayInput>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM