Creating a custom input component to search for documents with the same language as the current workspace.
Absolutely! You can filter reference inputs based on the current workspace/language by using the options.filter function on your reference field. This function has access to the document context, which you can use to match against the workspace language.
Here's how to set this up:
{
name: 'homepageReference',
type: 'reference',
to: [{type: 'page'}],
options: {
filter: ({document}) => {
// Get the current document's language
const currentLanguage = document.__i18n_lang || document.language
return {
filter: '_type == $type && __i18n_lang == $language',
params: {
type: 'page',
language: currentLanguage
}
}
}
}
}The key points here:
The
filterfunction receives context objects includingdocument,parent,value, andcurrentUser. You can usedocumentto access the current document's language field.Return both filter and params: As shown in the Sanity docs on reference filters, when using a filter function, you need to return an object containing both the
filter(GROQ query string) andparams(the parameter values).Match the language field name: The exact field name depends on how your document localization plugin stores language info. Common patterns:
__i18n_langfor the @sanity/document-internationalization pluginlanguagefor custom implementations- Check your plugin's documentation for the exact field name
Filter by document type and language: The GROQ filter
_type == $type && __i18n_lang == $languageensures you only see documents of the correct type AND matching language.
Alternative approach using the parent context:
If you're using this reference field inside an object or array, you might need to access the root document differently:
options: {
filter: ({document, parent}) => {
// For nested fields, traverse up to get the root document's language
const currentLanguage = document?.__i18n_lang || document?.language
return {
filter: '_type == $type && __i18n_lang == $language',
params: {
type: 'page',
language: currentLanguage
}
}
}
}This approach works great for multisite setups where workspace names match language IDs, and it will significantly clean up your reference selection UI by only showing relevant documents for the current language context!
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.