Like what we’re doing? Star us on GitHub!

Populate relationship field on click

Invest_it
2 months ago
3

Hello!



I have a relationship field with countries. I need to implement some logic to it. For example, click on a button and select all countries from the EU.



What is the best way to do it?



I see that there is a UI field where I can create custom react components, but I would like just to add this button with logic to native relationship component.



Thanks in advance!

  • patrikkozak
    Payload Team
    last month

    Hey @Invest_it ! You could implement this with a UI field if you'd like however a better alternative could be the following - using 3 fields:


    - Add a radio button to determine how to populate the field

    ["byGroup", "bySelection"]

    - When

    byGroup

    is selected - conditionally render a select with groups. Then you'd need to wire up a

    beforeChange

    hook to fetch and fill the relationship field with the ids of the ones in that group.


    - When an individual is selected: show the relationship field.



    What do you think?

  • KasparTr
    last month

    Great ideas! How do you create a filed hook that is reactively triggered based on the selection of another field tho? I can't seem get the field hooks to trigger when the same field is edited not to talk about when another field is updated.

  • Jarrod
    Payload Team
    last month

    @KasparTr you would have to use a custom component and update it based on the value of another field. We have some docs that go into detail describing our react hooks so you can tie into the state of the form and update the state of fields. Check em out here and let me know if you run into anything!



    https://payloadcms.com/docs/admin/hooks
Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More