#Filter elements in collection

2 messages · Page 1 of 1 (latest)

vernal lotus
#

Hey,

I have a collection where I want to show some blocks to the client only when certain conditions are met. I want to use ⁠req.context to pass a condition like ⁠sampleTest = 1. From what I understand, I can use the ⁠beforeRead hook at the collection level to alter the query.
⁠Condition is a block where I can specify ⁠name and ⁠value that must be met in order to return this element.
My collection has an ⁠elements array field where I can specify ⁠Condition or a sample ⁠InfoBarBlock.
My initial query to fetch the given ⁠ABTest element from the collection is:

const result = await cms.find({
  collection: "ab-tests",
  where: {
    id: {
      equals: "67ed05e57bcd6cb7d4dfbe45",
    },
  },

  context: {
    sampleTest: "1",
  },
});

I have no idea how to build such query.

Here you can find sample code for collection and blocks.

import type { Block, CollectionConfig } from "payload";
import { InfoBarBlock } from "../blocks/info-bar";

const Condition: Block = {
  slug: "condition",
  fields: [
    {
      type: "row",
      fields: [
        {
          type: "text",
          name: "name",
        },
        {
          type: "text",
          name: "value",
        },
      ],
    },
    {
      type: "blocks",
      name: "elements",
      minRows: 1,
      maxRows: 1,
      blocks: [InfoBarBlock],
    },
  ],
};



export const ABTests: CollectionConfig<"ab-tests"> = {
  slug: "ab-tests",
  fields: [
    {
      type: "blocks",
      name: "elements",
      blocks: [Condition, InfoBarBlock],
    },
  ],
};