Nested Reference Field - react-admin

In order to retrieve the equipment type I am using a that will retrieve the equipment model and then another that references the equipment type using the equipment model's field "typeID" to retrieve the equipment type.
However it displays the following warning:
Warning: Failed prop type: Invalid prop translateChoice of type
boolean supplied to ReferenceField, expected function.
The image represents the data model (an equipment has an equipment model, and an equipment model has an equipment type)

I found a better solution is kinda of an hack but seems to be more efficient.
Taking the question example where in order to get equipmentType is only needed <ReferenceField>, it would be something like this:
const EquipList = ({...props}) => {
<List {...props}>
<Datagrid>
<ReferenceFieldController label="Equipment Type" reference="equipmentModel" source="modelID" linkType={false}>
{({referenceRecord, ...props}) => (
<ReferenceField basePath="/equipmentModel" resource="equipmentModel" reference="equipmentType" source="typeID" record={referenceRecord || {}} linkType="show">
<TextField source="name" />
</ReferenceField>
)}
</RefenceFieldController>
</Datagrid>
</List>
}
In the example above <ReferenceFieldController> fetches the equipmentModel of equipment, as like <ReferenceField>. Label is needed because RA uses the first <ReferenceField> to show the column header in <Datagrid>, if you use internationalization you should apply translate function to the correct resource on this prop.
<ReferenceController> fetches the record and passes it as referenceRecord to a child function that will render the component for field presentation. Instead of presenting the field component you render a <ReferenceField> to fetch the nested relation and next you show the field. Since <ReferenceFieldController> only passes controller props to its child and the props of field component don't do what you want in the nested relation, you have to explicit pass them to <ReferenceField>. You need to pass record of <ReferenceField> as referenceRecord || {} because the initially the referenceRecord is not fetched yet and <ReferenceField> doesn't work with record as null.
Setting the linkType of <ReferenceFieldController> to false makes it not render a <Link> component that would redirect the user to an incorrect route.

Not a perfect fix, but to get around the translateChoice issue, you can create a wrapper and pluck out that prop to prevent it from being passed.
const SubReference = ({ translateChoice, children, ...props }) => (
<ReferenceField {...props}>{children}</ReferenceField>
);
While troubleshooting this, I was also receiving an error about nested a tags. I was able to silence the error by setting the linkType prop to false in the parent ReferenceField
<ReferenceField source="item_id" reference="list" linkType={false}>
<SubReference source="id_to_reference_from_list" reference="second_list">
<TextField source="name" />
</SubReference>
</ReferenceField>

I have the same problem and I think this is an actual bug. I commented on the corresponding github issue https://github.com/marmelab/react-admin/issues/2140
I looked into the code for ReferenceField and as far as I understood this is an actual bug. ReferenceField expects a function for the translateChoice property, but internally hands a boolean to ReferenceFieldView.
If you nest one ReferenceField into another the inner one receives false as translateChoice property and rightfully complains that it is a boolean and not a function.

Related

React-admin ReferenceInput pulling document id instead source field

Calling a ReferenceInput with an AutocompleteInput grabs the right document, and returns the "name" to the input but when you save it saves the document id to the source not the value of "name". Apparanetly React-admin does not allow anything but id to be saved natively, but the name is stored in the input until the document is saved. Is there any way to get the name from the input, and pass it to the format command maybe?
Expected result: input saves the value of the name from the document
<ReferenceInput label="Name" source="name" reference="profiles" filterToQuery={searchText => ({ name: searchText })} >
<AutocompleteInput optionText="name" source="name" resettable="true" shouldRenderSuggestions="true" />
</ReferenceInput>
This is correct - the default property of the object react-admin uses inside choice inputs (Select / Autocomplete) is the id. To override this behaviour you only have to pass one more prop to the <AutocompleteInput/> which is the optionValue e.g.:
<AutocompleteInput optionValue="name" ... />
And it should do exactly as you want it to.

React-Admin: How to make <Filter> mandatory with "alwaysOn" using "list"

I couldn't find a way to ONLY FETCH or LIST resources, when a user fills in the <SelectInput> (as rendered by <ReferenceInput>).
Due to a domain restriction,I need to ask the user to choose some Customer in order to query the Orders.
Is that possible? How can I pull it off?
To be clear, in their Demo project, the "Orders" can be listed using "Customer" as a <Filter>. (see image below)
A workaround could be also valid. Thanks.
Ok, this is an interesting scenario.
Let's closely look at the resource, and how it routes to various components.In this case, our interest is within the <list> and what exactly it renders:
// Set up the filter
const CustomerFilter = (props) => (
<Filter {...props}>
// setup your `ReferenceInput` and `SelectInput`
</Filter>
);
// Within your rendered component (OrderList)
<List {...props} filters={<CustomerFilter />}>
<Datagrid>
{console.log(props)} // Look out for the `match.params` prop
// ...
// Check for "customer_name" param within your props (verbose)
{match.params.customer &&
<TextField label="Customer" source="customer_name" />
}
</Datagrid>
</List>
Please note: don't just copy/paste this code. It's a verbose version.
The implication is that you can render customer name (or whatever) within your list depending on a passed parameter.

How can I prepopulate the structure of a complex nested form on the Create button in a List view in react-admin?

The List View of react-admin provides a "create (new record)" button out of the box when I specify a Create view in the Resource.
Since my record structure is nested up to three levels, containing objects with objects with arrays a.s.o., starting with an empty record (just {}) leads to a bunch of "undefined" errors in the validation function and when I test certain values with a FormDataConsumer to fold/unfold parts of the form based on other values.
I want my Create view to always start with a predefined record structure. How can I do that?
So it looks like you need default values for create form.
Documentation: https://marmelab.com/react-admin/CreateEdit.html#default-values
const postDefaultValue = { created_at: new Date(), nb_views: 0 };
export const PostCreate = (props) => (
<Create {...props}>
<SimpleForm initialValues={postDefaultValue}>
<TextInput source="title" />
<RichTextInput source="body" />
<NumberInput source="nb_views" />
</SimpleForm>
</Create>
);
You can flatten all the nested structure, and restore the input data back to the nested structure before submission. This document may help you: https://marmelab.com/react-admin/CreateEdit.html#altering-the-form-values-before-submitting

ArrayInput with SimpleFormIterator and conditional inputs

Let's say I have the following array in my create form
const CreateDefaults = {Inputs: [{id: "ID1", param: "a"},{id: "ID2", param: "b"}]};
and then I want to show extra TextInput only when id==="ID2"
export const MyCreate = withStyles(myStyles)(({ classes, ...props }) => (
<Create {...props}>
<SimpleForm defaultValue={CreateDefaults}>
<ArrayInput source="Inputs" {...props}>
<SimpleFormIterator {...props}>
<DisabledInput source="id" />
{/*this does not work*/}
{this.id === "ID2" ? (<TextInput source="ParamValue"/>) :null}
</SimpleFormIterator>
</ArrayInput>
</SimpleForm>
</Create>
));
How can I do something like that? I know that for the whole form, one can use FormDataConsumer. However, what can one do inside ArrayInput/SimpleFormIterator for each iteration?
How to access current object in iteration? I tried something like the answer given to the 'Custom Input do not receive record when inside ArrayInput' issue in the react-admin github page, but it still does not receive the record in custom input.
From the latest documentation here, you can see that if you use FormDataConsumer that is within an ArrayInput, you have a parameter called scopedFormData that you can use to get the current record and dereference that to get whatever fields you need. It usually also goes hand in hand with the getSource function you can use when setting the source within your FormDataConsumer.

How to populate a FlatList's header with data from the network?

I have a FlatList that displays a user's comments and I want to also populate the header with the user's profile (which is a different network call from the one fetching the comments).
Here's how render() looks like:
render() {
return (
<FlatList
data = {this.state.comments}
renderItem = {this.renderComment}
ListHeaderComponent={this.renderHeader}
keyExtractor={(comment, index) => comment.id}
/>
)
}
and then renderHeader looks like:
renderHeader() {
return (
<ProfileView user={this.state.profile} />
)
}
I use fetch in componentWillMount and then setState in order to get the data (this part works fine).
Now the error I get on the simulator is
undefined is not an object (evaluating 'this.state.profile')
but when I remove the renderHeader method, comments are fetched properly.
Since I'm very new to RN, can you help me understand what is wrong and how to fix it?
This looks like simply an issue with accessing context. When you run the renderHeader method called by the FlatList it doesn't know what this relates to.
So, you can simply set this.renderHeader = this.renderHeader.bind(this) in your constructor() method.
Alternatively, you should also be able to use an arrow function to call it, as this automatically refers to the correct this context.
ListHeaderComponent={() => this.renderHeader()}