React-admin: Change the record identifier from "id" to "userid" for example

Created on 28 Feb 2017  路  4Comments  路  Source: marmelab/react-admin

I am using admin-on-rest to build an admin panel for my webapp.

From the documentation at https://marmelab.com/admin-on-rest/ i did not find a way to change the identifier of the record of the rest API. it seems that the filed is always 'id'

How can I customize the code to do that?

Most helpful comment

You have to do it in a custom restClient (https://marmelab.com/admin-on-rest/RestClients.html), something like:

    const convertHTTPResponseToREST = (response, type, resource, params) => {
        const { headers, json } = response;
        switch (type) {
        case GET_LIST:
            return {
                data: json.map(x => { ...x, id: x.my_custom_identifier } ),
                total: parseInt(headers.get('content-range').split('/').pop(), 10),
            };
        case UPDATE:
        case DELETE:
        case GET_ONE:
           return { ...json, id: json.my_custom_identifier }; 
        case CREATE:
            return { ...params.data, id: json.my_custom_identifier };
        default:
            return json;
        }
    };

All 4 comments

You have to do it in a custom restClient (https://marmelab.com/admin-on-rest/RestClients.html), something like:

    const convertHTTPResponseToREST = (response, type, resource, params) => {
        const { headers, json } = response;
        switch (type) {
        case GET_LIST:
            return {
                data: json.map(x => { ...x, id: x.my_custom_identifier } ),
                total: parseInt(headers.get('content-range').split('/').pop(), 10),
            };
        case UPDATE:
        case DELETE:
        case GET_ONE:
           return { ...json, id: json.my_custom_identifier }; 
        case CREATE:
            return { ...params.data, id: json.my_custom_identifier };
        default:
            return json;
        }
    };

Thank you very much.

How I can mark it in the resource edit for example:

export const PostEdit = (props) => (
    <Edit title={<PostTitle />} {...props}>
        <SimpleForm>

            **<TextInput source="userid"  identifier=true />**

            <TextInput source="title" />
            <LongTextInput source="body" />
        </SimpleForm>
    </Edit>
);

So in the restClient props I will have this value and change the id dynamically.

@Dav7102: just use the id source instead of userid. @fzaninotto's code already handle the update part.

Here's a data provider that allows you to specify identifier names other than 'id' when you need it:
zachrybaker/ra-data-rest-client and in npm/ra-data-rest-client.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

phacks picture phacks  路  3Comments

ericwb picture ericwb  路  3Comments

aserrallerios picture aserrallerios  路  3Comments

pixelscripter picture pixelscripter  路  3Comments

kdabir picture kdabir  路  3Comments