--- layout: default title: "The ReferenceManyInput Component" --- # `` Use `` in an `` or `` view to edit one-to-many relationships, e.g. to edit the variants of a product in the product edition view. It's an [Enterprise Edition](https://react-admin-ee.marmelab.com)React Admin Enterprise Edition icon component, part of the `@react-admin/ra-relationships` package. `` fetches the related records, and renders them in a sub-form. When users add, remove or update related records, the `` component stores these changes locally. When the users actually submit the form, `` computes a diff with the existing relationship, and sends the related changes (additions, deletions, and updates) to the server. **Tip**: If you need to edit an array of *embedded* records, i.e. if the `variants` above are actually embedded in the `product` record, you should use [``](./ArrayInput.md) instead. **Tip**: If there is only one related record, you should use [``](./ReferenceOneInput.md) instead. ## Usage An example one-to-many relationship can be found in ecommerce systems: a product has many variants. ``` ┌───────────────┐ ┌──────────────┐ │ products │ │ variants │ │---------------│ │--------------│ │ id │───┐ │ id │ │ name │ └──╼│ product_id │ │ price │ │ sku │ │ category_id │ │ size │ └───────────────┘ │ color │ │ stock │ └──────────────┘ ``` You probably want to let users edit variants directly from the product Edition view (instead of having to go to the variant Edition view). `` allows to do that. ```jsx import { Edit, SimpleForm, TextInput, NumberInput, ReferenceInput, SelectInput, } from 'react-admin'; import { ReferenceManyInput } from '@react-admin/ra-relationships'; const ProductEdit = () => ( ); ``` `` requires a `reference` and a `target` prop to know which entity to fetch, and a child component (usually a [``](./SimpleFormIterator.md)) to edit the relationship. `` persists the changes in the reference records (variants in the above example) after persisting the changes in the main resource (product in the above example). This means that you can also use `` in `` views. **Tip**: `` cannot be used with `undoable` mutations. You have to set `mutationMode="optimistic"` or `mutationMode="pessimistic"` in the parent ``, as in the example above. **Tip**: `` uses the `disableReordering` prop in this example because the `variants` resource doesn't support reordering. If your reference table does have a `rank` column, you can leave sorting controls on (see [the `rankSource` section](#ranksource) for details). ## Props | Prop | Required | Type | Default | Description | | -------------- | -------- | ------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `target` | Required | `string` | - | Target field carrying the relationship on the referenced resource, e.g. 'user_id' | | `reference` | Required | `string` | - | The name of the resource for the referenced records, e.g. 'books' | | `children` | Required | `Element` | - | One or several elements that render a list of records based on a `ListContext` | | `label` | Optional | `string` | `reference` | Input label. In i18n apps, the label is passed to the `translate` function. Defaults to the humanized `source` when omitted. Set `label={false}` to hide the label. | | `helperText` | Optional | `string` | - | Text to be displayed under the input | | `source` | Optional | `string` | `id` | Name of the field that carries the identity of the current record, used as origin for the relationship | | `filter` | Optional | `Object` | - | Filters to use when fetching the related records, passed to `getManyReference()` | | `perPage` | Optional | `number` | 25 | Maximum number of referenced records to fetch | | `rankSource` | Optional | `string` | - | Name of the field used to store the rank of each item. When defined, it enables reordering of the items. | | `sort` | Optional | `{ field, order }` | `{ field: 'id', order: 'DESC' }` | Sort order to use when fetching the related records, passed to `getManyReference()` | | `defaultValue` | Optional | `array` | - | Default value of the input. | | `validate` | Optional | `Function` | `array` | - | Validation rules for the array. See the [Validation Documentation](./Validation.md) for details. | | `sx` | Optional | `SxProps` | - | Material UI shortcut for defining custom styles | ## `children` `` creates an ``, so it accepts the same type of children as ``: a Form iterator. React-admin bundles one such iterator: ``. It renders one row for each related record, giving the user the ability to add, remove, or edit related records. ```jsx ``` Check out [the `` documentation](./SimpleFormIterator.md) for more details. ## `defaultValue` When the current record has no related records, `` renders an empty list with an "Add" button to add related records. You can use the `defaultValue` prop to populate the list of related records in that case. It must be an array of objects. ```jsx ``` ## `filter` You can filter the query used to populate the current values. Use the `filter` prop for that. {% raw %} ```jsx ... ``` {% endraw %} ## `helperText` If you need to display a text below the input (usually to explain the expected data to the user), use the `helperText` prop. ```jsx ... ``` ## `label` By default, `` humanizes the `reference` name to build a label. You can customize the label by passing the `label` prop. ```jsx ... ``` React-admin uses [the i18n system](./Translation.md) to translate the label, so you can use translation keys to have one label for each language supported by the interface: ```jsx ... ``` ## `perPage` By default, react-admin restricts the possible values to 25 and displays no pagination control. You can change the limit by setting the `perPage` prop: ```jsx ... ``` ## `rankSource` `` provides controls to reorder the items in the list. If the related records have a numeric rank field, you can enable the reordering feature by setting the `rankSource` prop. For example, if the variants have a `rank` field, you can set the `rankSource` prop like this: ```jsx ``` Now the variants will be ordered by rank, and whenever the user changes the order of the items, `` will update the `rank` field of each item accordingly. Note that `` doesn't have the `disableReordering` prop in that case, to display the up/down controls. ## `reference` The name of the resource to fetch for the related records. For instance, if you want to display the `variants` of a given `product`, the `reference` name should be `variants`: ```jsx ... ``` ## `sort` By default, related records appear ordered by id desc. You can change this order by setting the `sort` prop (an object with `field` and `order` properties). {% raw %} ```jsx ... ``` {% endraw %} ## `source` By default, `` ferchers the `references` for which the `target` field equals the current record `id`. You can customize the field that carries the identity of the current record by setting the `source` prop. ```jsx ... ``` ## `sx` You can override the style of the root component (a Material UI [``](https://mui.com/material-ui/api/form-control/)) and its child components by setting the `sx` prop. {% raw %} ```jsx ... ``` {% endraw %} ## `target` Name of the field carrying the relationship on the referenced resource. For instance, if a `product` has many `variants`, and each variant resource exposes an `product_id` field, the `target` would be `author_id`. ```jsx ... ``` ## `validate` Just like regular inputs, you can use the `validate` prop to define custom validation rules for the list of references. ```jsx import { minLength } from 'react-admin'; const ProductEdit = () => ( ... ); ``` ## Limitations - `` cannot be used inside an `` or a ``. - `` does not support reordering its items so you should set the `disableReordering` prop on `` if you use it. - `` cannot be used with `undoable` mutations in a `` view. - `` cannot have a `` or a `` as one of its children. - `` does not support server side validation. ## Changing An Item's Value Programmatically You can leverage `react-hook-form`'s [`setValue`](https://react-hook-form.com/docs/useform/setvalue) method to change an item's value programmatically. However you need to know the `name` under which the input was registered in the form, and this name is dynamically generated depending on the index of the item in the array. To get the name of the input for a given index, you can leverage the `SourceContext` created by react-admin, which can be accessed using the `useSourceContext` hook. This context provides a `getSource` function that returns the effective `source` for an input in the current context, which you can use as input name for `setValue`. Here is an example where we leverage `getSource` and `setValue` to prefill the email input when the 'Prefill email' button is clicked: {% raw %} ```tsx import { SimpleFormIterator, TextInput, useSourceContext } from 'react-admin'; import { ReferenceManyInput } from '@react-admin/ra-relationships'; import { useFormContext } from 'react-hook-form'; import { Button } from '@mui/material'; const PrefillEmail = () => { const sourceContext = useSourceContext(); const { setValue, getValues } = useFormContext(); const onClick = () => { const firstName = getValues(sourceContext.getSource('first_name')); const lastName = getValues(sourceContext.getSource('last_name')); const email = `${ firstName ? firstName.toLowerCase() : '' }.${lastName ? lastName.toLowerCase() : ''}@school.com`; setValue(sourceContext.getSource('email'), email); }; return ( ); }; const StudentsInput = () => ( ); ``` {% endraw %} **Tip:** If you only need the item's index, you can leverage the [`useSimpleFormIteratorItem` hook](./SimpleFormIterator.md#getting-the-element-index) instead.