Conditional blocks in Payload CMS

442 views Asked by At

I'm exploring the development of a Payload CMS project featuring a collection of pages, each with a 'blocks' field. I aim to configure different block options based on the selected page type (for instance, 'home' or 'contact'). Is this level of customization feasible within Payload CMS? If it is, could you guide me on implementing this feature?

I attempted utilizing the 'condition' option within the component, yet it appears unable to modify the options within the blocks.

1

There are 1 answers

0
IveMadeAHugeMistake On

This is not currently supported in Payload. Your config will have to split up the blocks by the page type. For example:

export const Pages: CollectionConfig = {
  slug: 'pages',
  fields: [
    // ... your other fields
    {
      type: 'type',
      name: 'type',
      options: ['contact', 'home', 'post'],
    },
    {
      name: 'contactBlocks',
      type: 'blocks'
      blocks: [ /* all the block types you need for contact specifically */],
      admin: {
        condition: ({ type }) => type === 'contact',
      },
    },
    {
      name: 'homeBlocks',
      type: 'blocks'
      blocks: [ /* all the block types you need for home specifically */],
      admin: {
        condition: ({ type }) => type === 'home',
      },
    },
    {
      name: 'blocks',
      type: 'blocks'
      blocks: [ /* all the block types of any other page */],
      admin: {
        // if it doesn't contain 'contact' or 'home' specifically you can show the default blocks
        condition: ({ type }) => !['contact', 'home'].includes(data.type),
      },
    },
  ],
// ... the rest of the collection config
}

Then the frontend will need to render the blocks available based on the type.