Selecting one element in Select field changes the image shown in the media field?

default discord avatar
Arskeliss
7 months ago
7

Is it possible somehow, maybe with filters or relationship between select type and media type to connect them in a way that when I select one element from the dropdown list, then in the media field the image changes.



E.g. i select the word 'Cat' in the Select field then in the media field I get an image of a cat, that is already uploaded

  • default discord avatar
    generator101
    7 months ago

    you can probably use field hooks



    https://payloadcms.com/docs/hooks/fields
  • default discord avatar
    Arskeliss
    7 months ago

    I'll give it a try,thanks



    I cant really get hold of the concept of using hooks.


    Is it possible to read data from one field inside of a hook of another field?

  • discord user avatar
    jesschow
    Payload Team
    6 months ago

    Yes you can access the full document data from a hook, here is a list of the properties you can use:

    https://payloadcms.com/docs/hooks/fields#arguments-and-return-values

    Here is one way you can achieve this (screenshot), using a relationship field and hook that returns a different media based on the select field and the tags on the media item. I've used an

    afterRead

    hook here but you could use a different hook. Also the relationship field won't display the image, but you could add a custom component to this field that renders the image.

    Screen_Shot_2023-02-27_at_9.52.10_PM.png
  • default discord avatar
    Arskeliss
    6 months ago

    Thank you @jesschow, i will try it out soon, i'm sure that it will work this way. Thank you enormously.



    Also, sorry about being such a noob, I still have to understand Payload, to put the puzzle pieces together.



    Looks like a great opportunity as well to exercise writing custom components. Sweet. 🙌🙌🙌



    By the way, can I use something like Next's Image component to render the image inside Payload?



    It's working as expected, I changed the hook to afterChange and it changes the Media right after I hit the Save button. Neat. Thank you so much

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

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

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