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

Conditionally render fields based on a field value in a relationship

itsjxck
4 weeks ago
2

For example, lets assume I have 2 collections that are related;

Items

and

ItemTypes

.



ItemTypes

has a

name

text field and a

sellable

checkbox field:


const ItemTypes: CollectionConfig = {
  slug: "itemTypes",
  access: {
    read: () => true,
  },
  admin: {
    useAsTitle: "name",
    group: "Items",
  },
  fields: [
    {
      name: "name",
      type: "text",
      required: true,
    },
    {
      name: "sellable",
      type: "checkbox",
      defaultValue: false,
    },
  ],
};


Items

has a

name

text field, a

type

relation and a

sellPrice

field which I want to make only render when

type.sellable === true

:


const Items: CollectionConfig = {
  slug: "items",
  access: {
    read: () => true,
  },
  admin: {
    useAsTitle: "name",
    group: "Items",
  },
  fields: [
    {
      name: "name",
      type: "text",
      required: true,
    },
    {
      name: "type",
      type: "relationship",
      relationTo: ItemTypes.slug,
      hasMany: false,
      required: true,
    },
    {
      name: "sellPrice",
      type: "number",
      required: true,
      admin: {
        condition: (data) => data.type?.sellable,
      },
    },
  ],
};


How could I do this? In the

condition

of

sellPrice

, all I get is the id of the type rather than any of the info, and it doesn't accept an async function in order to lookup the id in the related collection.

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