How to filter an array of linked documents based on the current language context.
Based on the documentation I found, here's how to filter reference options by the current document's language when using the Document Internationalization plugin:
When you have an array of references and want to filter them to only show documents in the current language context, you can use the dynamic filter function on your reference field. The plugin uses special metadata fields like __i18n_lang to track document languages.
Here's how to set it up:
{
name: 'featuredEvents',
title: 'Featured Events',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'event'}],
options: {
filter: ({document}) => {
// Make sure to check if the language field exists
if (!document.__i18n_lang) {
return {
filter: '_type == $type',
params: {type: 'event'}
}
}
return {
filter: '_type == $type && __i18n_lang == $lang',
params: {
type: 'event',
lang: document.__i18n_lang
}
}
}
}
}
]
}Key points:
- The
filteroption accepts a function that receives an object containingdocument,parent, andparentPathproperties - The current document's language is stored in
document.__i18n_langwhen using the Document Internationalization plugin - You can use this value in your GROQ filter to match only documents with the same
__i18n_langvalue - Always check if the property exists before using it to avoid errors
This will ensure that when editors are adding items to the featured events list, they'll only see events that match the current document's language context.
The reference field documentation has more details on using dynamic filters, and you can learn more about the Document Internationalization plugin's structure in the internationalization docs.
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.