Filter array of references by field value in same document
You're looking for how to filter reference options based on a field in the current document - this is definitely possible! You'll want to use the options.filter function on your reference field.
Here's how to set this up for your portfolio use case:
{
name: 'projectGroup',
type: 'document',
fields: [
{
name: 'area',
type: 'string',
title: 'Area',
options: {
list: [
{title: 'Visual Communication', value: 'visual'},
{title: 'Product Design', value: 'product'},
{title: 'Environmental Design', value: 'environmental'}
]
}
},
{
name: 'projects',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'project'}],
options: {
filter: ({document}) => {
// Only show projects that match the selected area
if (!document.area) {
return {
filter: 'area == $area',
params: {area: null} // or show all if no area selected
}
}
return {
filter: 'area == $area',
params: {area: document.area}
}
}
}
}
]
}
]
}The options.filter function receives an object with properties like document, parent, and value, and returns an object with:
filter: A GROQ filter stringparams: Parameters to use in the filter (helps prevent injection issues)
So in your case, when you select "Visual Communication" in the area field, only projects with area == 'visual' will appear when you go to add references to the projects array.
You could also combine this with conditional fields if you wanted to hide the projects field entirely until an area is selected:
{
name: 'projects',
type: 'array',
hidden: ({document}) => !document?.area,
// ... rest of config
}This pattern works great for creating filtered, contextual editing experiences where you're building relationships between documents based on shared taxonomy or categorization fields!
Show original thread10 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.