Lookup value from relation from condition callback

default discord avatar
jmrkll2 years ago
1 1

For a condition callback of a field I need to get the value of a relation of another field. In code I need to do something like that:

const val = await payload.findById({ collection: 'thecol', id: theId, depth: 1 })

The problem is, that payload is not initialized in the callback. req.payload is not available in this callback. Is it possible to get a valid pointer for it? Do I have to get the value by doing a fetch() to localhost?

Thank you very much in advance.
Kind regards,
Johannes

  • Selected Answer
    discord user avatar
    jmikrut
    2 years ago

    Hey @Salomo — I can give you some pointers here!

    So, payload.findByID is a local API method, which means it's only available in contexts where you're executing code on your server. As conditions are executed in the browser, those local API methods are not available.

    Instead, you should just do a fetch. Which, if you think about it, because you're in the browser—that's really the only way to do something like that.

    One note though—field conditions are run quite frequently, because every time a field value changes, you need to run the condition. For a use case like this, I'd probably build a custom component, where you can make that fetch much less frequently. That would be more performant.

    What kind of field needs this type of condition? As of payload@0.14.0, you can easily import and re-use some of Payload's built-in field types by importing them like this:

    import { TextInput, SelectInput } from 'payload/components/forms'

    Then you would just "wrap" the built-in Payload component with your own logic, showing and hiding the field accordingly.

    We will be exposing more and more built-in field types so if you need a field type that's not currently exposed, let us know and we will add it.

    👍

    1 reply
  • default discord avatar
    jmrkll2 years ago

    Hi @jmikrut,

    thanks for your explanation. I already feared about the performance impact of the fetch() solution.

    The custom component might be a good idea. I have a select field to choose a category item from a relation to another collections. Depending of the value of the chosen category other fields will be available or not. These other fields need to know the value of the select field, not the id of the referenced collections. The select component needs to get the values when loading the page anyway. Maybe there is a way to get these values from the other condition callbacks.

    I’ll give it a try.

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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