Setting up schema with references to filter categories by project in Sanity.io

4 replies
Last updated: Jul 6, 2020
Hi! I’m trying to set up a schema where a particular data type has references to two other data types, “projects” and “categories”. The category data type also has a reference to a “project”. What I’d like to do is to apply a filter to my reference to (type: “category”) that only shows categories that have a reference to the same project I’ve already selected. This: https://www.sanity.io/docs/reference-type#additional-dynamic-filter-8118f73f6758 – seems close to what I want to do, but I can’t figure out how to modify it to work with references. Thanks!
Jul 6, 2020, 5:27 AM
Hi Dan, something like this should work. In the example I’ve assumed that the category type has a reference field called
project
.

...
fields: [
  {
    name: 'project',
    title: 'Project',
    type: 'reference',
    to: {type: 'project'}
  },
  {
    name: 'category',
    title: 'Category',
    type: 'reference',
    to: {type: 'category'},
    options: {
      filter: ({document}) => {
        if (!document.project) {
          return
        }
        return {
          filter: 'project._ref == $project',
          params: {
            project: document.project._ref
          }
        }
      }
    }
  }
]
Jul 6, 2020, 9:34 AM
Thanks so much! That helps a lot. One further complication I made for myself: what if “project” is not just a _ref but an array of _refs?
Jul 6, 2020, 10:30 AM
Figured it out, thanks! Thanks for the pointer.
Jul 6, 2020, 10:47 AM
Awesome, glad to hear! 🙂
Jul 6, 2020, 10:54 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?