Search code examples
keystonejs

How to show/hide fields in the admin UI depending on the value from another field with KeystoneJS Next?


I have a Category model set in schema.ts as follows:

Category: list({
  fields: {
    name: text(),
    type: select({
      options: [
        { label: "MultipleChoice", value: "MultipleChoice" },
        { label: "Range", value: "Range" },
      ],
      defaultValue: "...",
      isRequired: true,
      isUnique: true,
      ui: { displayMode: "segmented-control" },
    }),
    from: integer(),
    to: integer(),
    options: text()
  },
})

And this renders these components in the admin UI:

components in admin UI

I'd like to show from and to fields only when Range is selected (hiding options field) and the other way around when MultipleChoice is selected. Is there a way to achieve that with Keystone Next?

I also tried another approach splitting the category types in different models and then relate them somehow with the Category model, but I'm not sure how to do so. Something like:

CategoryRange: list({
  ui: {
    isHidden: true,
  },
  fields: {
    from: integer(),
    to: integer(),
  },
}),
CategoryMultipleChoice: list({
  ui: {
    isHidden: true,
  },
  fields: {
    options: text(),
  },
})

Solution

  • Conditional fields were supported in Keystone 4. They haven't been brought forward to Keystone 6 (aka. "Next") yet but they're on the roadmap. I'd expect support for them to arrive in the next few months.

    Right now, in Keystone 6, probably the best you could do would be to create a custom field type that collected the "type" and "from/to" fields together. This would let you define an interface in the Admin UI that implemented whatever presentation rules you liked.