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.
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?
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.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.