Return data in relationship field related just to collection selected

default discord avatar
akacronos10 months ago
2

I have a collection, where i want to select data from a relationship field, but i want to display just data related to the visitType (activity or community options).



Is this posible, just show data from activities if visitType is activity?




{
      name: 'visitType',
      label: 'Tipo de visita',
      type: 'select',
      index: true,
      options: [
        {
          label: 'General',
          value: 'general',
        },
        {
          label: 'Espacio',
          value: 'space',
        },
        {
          label: 'Actividad',
          value: 'activity',
        },
        {
          label: 'Comunidad',
          value: 'community',
        },
      ],
    },
{
      name: 'activity',
      type: 'relationship',
      label: 'Actividad',
      relationTo: ['activities', 'community'],
      index: true,
      filterOptions: ({ relationTo, data, siblingData }) => {
        if (siblingData?.visitType === 'activity') {
          return {
            // data from activities collection
          };
        }

        if (siblingData?.visitType === 'community') {
          return {
            // data from comunity collection
          };
        }
      },
    },
  • discord user avatar
    dribbens
    10 months ago

    Filter Options can return a

    where

    query

    https://payloadcms.com/docs/fields/relationship#example

    You'll need the return object to discriminate the type for you. One way would be to add a new property with the same name on both collections in your

    relationTo

    so that you can say

    type: { equals: "activity" }

    or

    type: { equals: "community" }

    for example. It would make sense to make this a hidden field with a defaultValue so that it is not in the admin UI at all.



    You may not need a new field to act as the discriminator if you have some existing fields that both collections share that have distinct options which can be queried that can serve this same purpose.



    Alternatively you might simplify your approach by breaking your one relationship field down into two different fields that you conditionally render based on the visitType, each with a relationTo the corresponding collection.

  • default discord avatar
    akacronos10 months ago

    Thanks @dribbens , that's what I thought. Sadly they don't share any field. I'm going to consider the two different fields, but I wold need to change some parts in the front, to be able to read the url from the relationships (activity/community), but maybe it's not that dificult.

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.