9

Is there any way to use a different reference field (other than id) for a ReferenceInput?

For example:
I have a languages resource, which I want to populate using a language_code field.
Note, I don't want to use the id field of languages, I want to use the code field.

I have managed to get it to work by using the following:

<ReferenceInput 
  label="Language code" 
  source="language_code" 
  reference="languages"
>
  <SelectInput optionText="name" optionValue="code" />
</ReferenceInput>

The only problem with this is that:

After selecting a language from the select input, the ReferenceInput tries to fetch the resource using the code field rather than the id field, which returns a 404 error.

Towkir
  • 3,889
  • 2
  • 22
  • 41
Ross
  • 135
  • 1
  • 8
  • Do you mean it tries to fetch using the `id` field instead of the `code` field ? – Gildas Garcia Jun 27 '18 at 17:41
  • No, it uses the `code` field (I assume because the `optionValue` is set to `code` so it populates the `ReferenceInput` with the code). So it fetches `languages/en` rather and `languages/1`. This fails because the `languages` endpoint expects an `id` in the URL and not a code. – Ross Jun 28 '18 at 12:55

2 Answers2

1

The value stored as the reference to the languages in the resource must be its identifier. Indeed, if you add a ReferenceField in the show view of your resource, how can it fetch the language without its id ?

You have two options here:

  • make your API support the languages/en route
  • store the language_id in addition to the language_code in your resource and create a custom ReferenceInput which will return both values after selection
Gildas Garcia
  • 6,966
  • 3
  • 15
  • 29
0

Do we know the underlying reason why we use "id" field for the <ReferenceInput>?

On that note, here's an official explanation from react-admin.
IMO, if we catch that bit from react-admin then we can (try to) use any other field, maybe !

In your case, fetches data, and delegates rendering down to <SelectInput> to which it passes the possible choices as the choices attribute. This works fine since you are able to select a "language".

Are you aware that optionValue="id" is the default?

Two possible solutions:

  • Remove optionValue="code"

  • Can you find a way to map your "code" to an "id"?
    Remember in this case <SelectInput> populates it's choices prop from <ReferenceInput>,
    choices=[{id='', value=''}, {...}]

MwamiTovi
  • 2,425
  • 17
  • 25