How to get relationship field's targeted collection in Admin UI

default discord avatar
last year
1 1

Hi everyone,
Currently I'm trying to explore developing plugin in Payload to add UI fields on multiple collections. When going into specific collection in admin, it's possible to get other fields' value using useWatchForm(). But (1-1) relationship field only return id of the referred doc, without knowing where it's come from. Is there any way to get this done?

The only work around I found currently is all relationship field change to multiple:
relationTo: 'targetCollection' => relationTo: ['targetCollection']
hence the value the field will change from id only to {value: id, relationTo: 'targetCollection'} But this kind of adding unnecessary data in the collection.

  • discord user avatar
    Payload Team
    last year

    Hey @khakimvinh — I'm following what you are looking to do.

    I would avoid changing the fields to multiple like you said, because like you noticed, that changes the shape of the data. You probably want your plugin to handle all four types of relationship field data.

    You can access the config for the collection you're working in, and find the relevant field that corresponds to the field that you're interacting with.

    // import the hook
    import { useConfig } from 'payload/components/utilities';
    // use it in your React component
    const config = useConfig();

    Could you do that? To find the field recursively, you would need to parse the field's path that you are trying to work with. For example, top-level relationship fields like myRelationshipField would just have a path like that - myRelationshipField.

    But, nested fields, like say one within an array, would have a path like someArrayField.0.myRelationshipField. And you'd need to take that path, and then traverse the collection config to find the field config itself. Then you could access the relationTo.

    Does that make sense?

    1 reply
  • default discord avatar
    last year

    Thanks a lot! I end up looking around and found useDocumentInfo() in utilities, which is exactly what I need. This hook return current active collection, with that the rest is all good! Also, I would suggest adding these amazing hooks into the current Payload doc.

Open the post
Continue the discussion in GitHub
Like what we're doing?
Star us on GitHub!


Connect with the Payload Community on Discord



Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.