Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Conditionally render fields based on a field value in a relationship

default discord avatar
itsjxck2 years ago
1

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.

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.