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.
Related
I would like to create a DataGrid where only component that have a certain property can be expanded. For example:
comments: [
{ id: 0, author: 'a', text: 'no', responses:[2]},
{ id: 1, author: 'b', text: 'yes' },
{ id: 2, author: 'b', text: 'perhaps' }
]
I would like to display this array, but only first option would be expandable, since it's the only one that has responses. Is there a way of achieving that without rewriting the DataGrid?
Unfortunately no. I would suggest to display an empty state component instead.
Edit
Here is an extract from the documentation:
By default, <Datagrid> renders its body using <DatagridBody>, an internal react-admin component. You can pass a custom component as the body prop to override that default. Besides, <DatagridBody> has a row prop set to <DatagridRow> by default for the same purpose. <DatagridRow> receives the row record, the resource, and a copy of the <Datagrid> children. That means you can create custom datagrid logic without copying several components from the react-admin source.
My suggestion would be to copy the original <DatagridRow> component and add an isExpandable prop accepting a function which will be called with the row record to conditionnaly display the expand button.
You could then use this custom DatagridRow like this:
import MyDatagridRow from './MyDatagridRow`;
const MyDatagridBody = props => <DatagridBody {...props} row={<MyDatagridRow />} />;
const MyDatagrid = props => <Datagrid {...props} body={<MyDatagridBody />} />;
However, as we already have an isSelectable prop, I also suggest to open a new feature request issue on react-admin repository to add an isExpandable prop.
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.
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
We have the following that displays a select style UX:
<ReferenceInput source="visibility.visibilityId" reference="projectVisibilities" allowEmpty>
<SelectInput optionText="visibility" />
</ReferenceInput>
We want to add in parentheses the description within visibility.
Something like this :
<ReferenceInput source="visibility.visibilityId" reference="projectVisibilities" allowEmpty>
<SelectInput optionText={["visibility", "(", "description", ")" } />
</ReferenceInput>
An unfound string would be rendered as a regular string and visibility and description as the optionText of the select input, after joining the array.
Is this something already possible?
optionText accepts a function, so you can shape the option text at will:
const optionRenderer = choice => `${choice.visibility} (${choice.description})`;
<SelectInput optionText={optionRenderer} />
optionText even accepts a React Element, that will be cloned and receive the related choice as the record prop. You can use Field components there:
const DescriptionField = ({ record }) => <span>{record.visibility} ({record.description})</span>;
<SelectInput optionText={<DescriptionField />}/>
Note that this is clearly documented in the React-admin documentation:
https://marmelab.com/react-admin/Inputs.html#selectinput
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.