react-admin icon indicating copy to clipboard operation
react-admin copied to clipboard

Cannot use two reference fields to the same resource

Open binhfoto opened this issue 9 years ago • 12 comments

Hi , I want to display more than one field of referenced record so I define like this

<List {...props} title="Storage List">

        <Datagrid>

            <ReferenceField label="Name" source="productId" reference="products">
                <TextField source="name"  style={GridStyle}/>
            </ReferenceField>

            <ReferenceField label="Unit" source="productId" reference="products">
                <TextField source="unit"  style={GridStyle}/>
            </ReferenceField>            

            <EditButton />

        </Datagrid>

    </List>

This one get error bundle.js:2115 Warning: flattenChildren(...): Encountered two children with the same key, 584b7d3cdcb35d34e35640d2-productId. Child keys must be unique; when two children share a key, only the first child will be used.

Are there any way to solve this? I'm on version "admin-on-rest": "^0.5.4", and quite new to admin-on-rest.

Thank you very much.

binhfoto avatar Dec 10 '16 06:12 binhfoto

You're referencing a product two times. The generated ids are the product ids. You should introduce a new Unit model

djhi avatar Dec 10 '16 08:12 djhi

But that's a bug anyway. We'll look into it.

djhi avatar Dec 10 '16 08:12 djhi

I misread your code. I'll check how to do that.

djhi avatar Dec 10 '16 08:12 djhi

Thank djhi.

binhfoto avatar Dec 10 '16 10:12 binhfoto

While we could support that, you must be aware that adding two reference fields tells admin-on-rest fetch the related object twice. That's not a good thing performance wise.

Until this is made possible (or until we make it impossible, I have yet to make up my mind), you can still display more than one field of the related object using the <FunctionField>:

<List {...props} title="Storage List">
  <Datagrid>
    <ReferenceField label="Unit" source="productId" reference="products">

      <FunctionField render={record => `${record.name} ${record.unit}` } />

    </ReferenceField>            
    <EditButton />
  </Datagrid>
</List>

fzaninotto avatar Dec 13 '16 17:12 fzaninotto

@djhi

Please do not make this impossible; in fact expanding on the idea would make a really great UX feature.

It's quite common when linking objects to want to pull back more than one field to distinguish it. Even better is to push beyond one hop so you can link to objects multiple hops away. And the icing on the cake would be multikey references.

I'd love to see some encapsulation method where you first updated the props the Datagrid will receive before it's rendered. The linked objects would become named fields on the props objects.

Please forgive my lack of JsxReactFoo here; I envision something like this: [ EDIT:

  • Added comments to more clearly explain exactly what each line is doing
  • Reconfigured the way the double reference to "emergencyContacts" is described to make it clearer "primaryContact" and "secondaryContact" are the "reference" identifiers for the Datagrid; and that "emergencyContacts" is the "resource_name" used to look them up
  • Added a "Double hop" through the "emergencyContacts" reference to get to "contactInfo"
  • The assumed requirement is that each "reference" must be declared before it can used as a source

]

<List {...props} title="Storage List">
  <Datagrid
    ReferenceLinks={ [
        // Preventing the 'double retrieve' problem by linking the resource item as a fieldName in props
        {"reference": "products", "link": {"productId":props["proudctId"]} }, 
        // props["products"] = products[] 
        //        where products["productId"] === props["productId"];

        // Adding a resource item to props where the key field names aren't the same
        {"reference": "users", "link": {"userId":props["ownerId"]} },
        // props["users"] = users[] 
        //        where users["userId"] === props["ownerId"];


        // Creating a "made up" reference name so we can "double reference" the same resource pool
        // Using two primary keys (as filters) to determine which resource item to reference
        // Using a hard coded value in place of props[fieldName] to associate the resource item
        {"reference": "primaryContact", 
            "resource_name": "emergencyContacts", 
            "link": { "userId":props["ownerId"], "priority":1 },
        },
        // props["primaryContact"] = emergencyContacts[] 
        //        where emergencyContacts["userId"] === props["ownerId"] \
        //                && emergencyContacts["priority"] === 1; 


        // Creating a "double reference" to "emergencyContacts" stored in a "made up" reference name
        {"reference": "secondaryContact", 
            "resource_name": "emergencyContacts",
            "link": {"userId":props["ownerId"], "priority": 2 },
        },
        // Same as "primaryContact" but this is "secondaryContact" using a '2' for "priority"
        // props["secondaryContact"] = emergencyContacts[] 
        //        where emergencyContacts["userId"] === props["ownerId"] \
        //                && emergencyContacts["priority"] === 2;


        // And finally; a "Double Hop" through "emergencyContacts" to get to the "contactInfo" resource
        {"reference": "primaryContactInfo", 
            "resource_name": "contactInfo", 
            "link": {"contactId": props["primaryContact"]["contactId"] },
        },
        // props["primaryContactInfo"] = contactInfo[] 
        //        where contactInfo["contactId"] === props["primaryContact"]["contactId"] 
        // ** This works because props["primaryContact"] was earlier assigned by a prior link **

        // Doing the same again for the secondaryContact
        {"reference": "secondaryContactInfo", 
            "resource_name": "contactInfo",
            "link": {"contactId": props["secondaryContact"]["contactId"] },
        },
        // props["secondaryContactInfo"] = contactInfo[] 
        //        where contactInfo["contactId"] === props["secondaryContact"]["contactId"] 
        // ** This works because props["secondaryContact"] was earlier assigned by a prior link **
    ] }
  >
// And now we get to _use_ all those new references we just added :)
// users.name
          <ReferenceField label="Name" reference="users">
                <TextField source="name"  style={GridStyle}/>
            </ReferenceField>
// products.unit
            <ReferenceField label="Unit" reference="products">
                <TextField source="unit"  style={GridStyle}/>
            </ReferenceField>            

// primaryContactInfo.name, primaryContactInfo.phone
            <ReferenceField label="Primary Name" reference="primaryContactInfo">
                <TextField source="name"  style={GridStyle}/>
            </ReferenceField>            
            <ReferenceField label="Primary Phone" reference="primaryContactInfo">
                <TextField source="phone"  style={GridStyle}/>
            </ReferenceField>            

// seondaryContactInfo.name, secondaryContactInfo.phone
            <ReferenceField label="Secondary Name" reference="secondaryContactInfo">
                <TextField source="name"  style={GridStyle}/>
            </ReferenceField>
            <ReferenceField label="Secondary Phone" reference="secondaryContactInfo">
                <TextField source="phone"  style={GridStyle}/>
            </ReferenceField>            

    <EditButton />
  </Datagrid>
</List>

This gives us a way to add references as named fields on props before calling Datagrid's render. With this kind of "referenceability" linking a record to all it's related "descendants" is very powerful.

What I'm not clear about though is whether or not these "ReferenceLinks" belong: A) In the DataGrid as described here B) As part of the encapsulating "List" itself C) As a descriptor inside the Admin object itself D) Both the Admin for "Built-In" relationships; and the Datgrid for "Ad-Hoc" views

Thanks!!! This framework is awesome!!

MikeFair avatar Feb 27 '17 01:02 MikeFair

Fetching references isn't the responsibility of the <List> or the <Datagrid>, it's the responsibility of a Field component. Prebrowsing all fields in the List to look for References is an anti-pattern (we've done this in ng-admin and it's a mess).

So nothing is impossible ; in fact, you could probably implement more complex <ReferenceField> components yourself, even a <TwoHopsReferenceField>. Give it a try!

fzaninotto avatar Feb 27 '17 22:02 fzaninotto

@fzaninotto

Well first off, this is too awesome for me to say too much at the moment, but it seems the <Datagrid> is missing that second dimension of <ResourceItem> that each row is describing.

The <Field> components in the grid, seem much more like a <DataColumn> of the Datagrid than a <FieldItem> of the Resource Record, but I might change my mind as I play with it more. I've always found grids are kind of weird to properly express in a either a hierarchy or flat namespace because there's that dual nature of the "Row" that is both a specific renderable thing that hosts columns and an abstract data object to be rendered at the same time.

Each <Resource> described in the <Admin> object lives as part of a directed graph. The thing I see missing, that's directly related here is a series of <ResourceLinks> that are children of the <Resource> object in the <Admin> component.

Prebrowsing all fields in the List to look for References is an anti-pattern

I agree that prebrowsing through child nodes is an anti-pattern. That's what that 'wall-of-text' "ReferenceLinks" object eliminates. For each resource row it describes exactly what to fetch, where to fetch it from, how to fetch it (criteria to use), and where to stick the results once they arrive. It links everything to the current record object (which the example assumes is "props").

With one pass through the ResourceLinks a "fetch chain" is memorized and on every row, all the link requests execute in parallel (with dependencies automatically triggering as the data comes back).

This is the only part that really makes me want to avoid using the feature:

... adding two reference fields tells admin-on-rest fetch the related object twice. That's not a good thing performance wise.

Other than that, I'm really looking forward to see what this can be made to do!

Thanks!!

MikeFair avatar Mar 01 '17 00:03 MikeFair

+1 I really want this functionality. I want to make a "related data" view, where I can quickly see, for example, the user who made a specific comment, without navigating away from the comment. I haven't come up with an alternative way, but for sure some kind of RecordReference component would solve this.

olavim avatar May 09 '17 17:05 olavim

+1 on this. I want to display a datagrid of conversations between two users. Right now, I can't fetch both the sender and receiver using a ReferenceFIeld, as they use the same reference users.

glenncampioni avatar Nov 29 '17 15:11 glenncampioni

+1 on this too. While @fzaninotto suggestion of using a FunctionField is fine, this does not allow us to have 2 different columns on the datagrid, with separate sort, etc.

Would you consider implementing a solution?

afilp avatar Jan 29 '18 00:01 afilp

I've tested again, this works fine both on master and next. The flattenChildren error was fixed some time ago.

On mont, the <ReferenceField> component dispatches a CRUD_GET_MANY_ACCUMULATE action, which is accumulated and deduplicated by the referenceFetch saga. Once all the <ReferenceField> elements have finished mounting, the saga emits a single, aggregated, CRUD_GET_MANY action.

This means that whatever the number of reference fields you have in a datagrid, they will be displayed correctly, without adding another request to the restClient.

fzaninotto avatar Feb 15 '18 10:02 fzaninotto