Reputation: 520
I want to use the value of a field of my record to filter some autocomplete options, but I don't know how to get the value to use it.
<ReferenceInput source="text_resume_template_id" reference="text_templates"
filter={{ "client_id": my_client_id_value }}>
<AutocompleteInput optionText="name" />
</ReferenceInput>
On the record I'm editing, I have the "client_id" field, what I want is to get the value from this field and put it in my_client_id_value
.
I know that if I wanted to use the id of the record I'm editing, I would use:
export const ReportsEdit = () => {
const { id } = useParams()
return (...
I React-Admin version 3.xx I think I would use something like: (using props)
export const ClientsShow = props => {
return (
<Edit {...props}>
<ReferenceInput source="text_resume_template_id" reference="text_templates"
filter={{ "client_id": props.client_id }}>
<AutocompleteInput optionText="name" />
</ReferenceInput>
How can I get the value client_id from my record and use it as a filter?
Upvotes: 0
Views: 1084
Reputation: 520
I found my answer in the Show View documentation and I was not expecting to find it there because I'm working in the Edit.
I tried the UserContextProvider
I found in other parts, but I couldn't make it work.
The solution I used:
import {Edit, ReferenceInput, AutocompleteInput,
useGetOne, useRedirect, RecordContextProvider } from 'react-admin';
export const ReportsEdit = () => {
const { id } = useParams();
const redirect = useRedirect();
const { data, isLoading } = useGetOne(
'reports',
{ id },
{ onError: () => redirect('/reports') }
);
if (isLoading) { return <div />; }
return (
<RecordContextProvider value={data}>
<Edit>
<ReferenceInput flex={1} source="text_resume_template_id" reference="text_templates"
filter={{ "client_id": data.client_config._id }} >
<AutocompleteInput optionText="name" /></ReferenceInput>
</Edit></RecordContextProvider>
It worked, but I wonder if other option exists, without the need of the RecordContextProvider
(because the Edit
already have access to the record data).
If anyone have other answer, would be nice.
UPDATE:
Another option: Using formData to get the selected values from a field (no need to get from record, useful to Create views and more flexible for Edit). The advantage is that if you change the field value, the filter will be update (the previous option would only change if the record changed)
import {
Edit, ReferenceInput, AutocompleteInput, FormDataConsumer
} from 'react-admin';
export const ReportsEdit = () => {
return (
<Edit>
<ReferenceInput source="client_id" reference="clients">
<AutocompleteInput optionText="client_name" isRequired />
</ReferenceInput>
<FormDataConsumer>
{({ formData }) =>
<ReferenceInput source="text_resume_template_id" reference="text_templates"
filter={{ "client_id": formData.client_id }} >
<AutocompleteInput optionText="name" /></ReferenceInput>
}
</FormDataConsumer>
</Edit>
Upvotes: 2