#Optimizing Collections with Conditional Fields

11 messages · Page 1 of 1 (latest)

tawny tangleBOT
#

Is there a way to import and build a collection from parts?
In pages collection I have a select field and depending on a selection there is a different setup. So the file become huge.
slug: "pages",
admin: {
group: "Content",
useAsTitle: "title",
},
access: {
read: () => true,
},
fields: [
{
name: "title",
label: "Page name",
type: "text",
required: true,
},
{
name: "pageSetup",
label: "Page Setup",
type: "select",
options: ["a", "b", "c", "d"],
},
(all the fields for option a)
(all the fields for option b)
(all the fields for option c)
(all the fields for option d)

crystal marshBOT
#

Original message from @versed rune - Moved from #general message

pseudo musk
#

What exactly do you mean by "parts"? @versed rune

rough pendant
#

i don't think it's specific to payload question but rather to your implementation here
you could just have files like
fields-a.ts that exports an array of fields for option "a"
fields-b.ts and so on

versed rune
#

i was trying to spread the array like
...fields.a

pseudo musk
#

This sounds like the pattern you were going for

versed rune
# pseudo musk

I believe so
I am not sure why im getting the rror though maybe its because the fields are conditional

rough pendant
#

can go with this helper just to not repeat, no any errors as well

const fieldsWithCondition = ({ condition, fields }: { condition: Condition; fields: Field[] }) => {
  return fields.map(
    (each) =>
      ({
        ...each,
        admin: {
          ...(each.admin ?? {}),
          condition,
        },
      }) as Field,
  );
};

export const fieldsA = fieldsWithCondition({
  condition: (data) => data.pageSetup === 'a',
  fields: [
    {
      name: 'textForA',
      type: 'text',
    },
  ],
});

export const Collection: CollectionConfig = {
  fields: [
    {
      label: 'Page name',
      name: 'title',
      required: true,
      type: 'text',
    },
    {
      label: 'Page Setup',
      name: 'pageSetup',
      options: ['a', 'b', 'c', 'd'],
      type: 'select',
    },
    ...fieldsA,
  ],
  slug: 'pages',
};