Dynamic filters with reference to multiple types in Sanity
Yes, you can definitely implement dynamic filters and reference multiple types at the same time in Sanity! Your example code is on the right track, but you'll need to apply it to an array of references instead of a single reference field.
Array of References with Dynamic Filter
{
title: 'Directors',
name: 'directors',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'person'}],
options: {
filter: ({document}) => {
if (!document.releaseYear) {
return {
filter: 'role == $role',
params: {role: 'director'}
}
}
return {
filter: 'role == $role && birthYear >= $minYear',
params: {
role: 'director',
minYear: document.releaseYear
}
}
}
}
}
]
}Multiple Reference Types with Dynamic Filters
If you want to reference multiple document types with different filters for each:
{
title: 'Crew Members',
name: 'crewMembers',
type: 'array',
of: [
{
type: 'reference',
to: [
{type: 'person'},
{type: 'company'}
],
options: {
filter: ({document}) => {
if (!document.releaseYear) {
return {
filter: '_type in ["person", "company"]',
params: {}
}
}
return {
filter: '(_type == "person" && birthYear >= $minYear) || _type == "company"',
params: {
minYear: document.releaseYear
}
}
}
}
}
]
}Key Points
- The
options.filtergoes inside each reference definition within theofarray, not on the array itself - Dynamic filters work the same way - they receive
{document, parent, parentPath}and return{filter, params} - Multiple types in
to- you can reference multiple document types and filter across all of them using an array like[{type: 'person'}, {type: 'bovinae'}] - Type-specific filtering - use
_type == "typename"in your GROQ filter to apply different logic per type
The filter function has access to the parent document, so you can create conditional logic based on any field in your document, just like in your example with releaseYear.
According to the Sanity reference type documentation, the filter option can be either a string or a function. When you provide a function, it's called with an object containing document, parent, and parentPath properties, and it should return an object with filter and params properties. This works perfectly for arrays of references!
Show original thread13 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.