🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to filter an array of linked documents based on the current language context.

4 replies
Last updated: Dec 13, 2023
Studio: Localized array references?Hey all,
🖐️ I am facing an issue with an array of linked documents (A featured Events List). The field lets me choose both languages, even though I am editing the current page in one specific language. How can I achieve – when users adding new items to the list –, to get rid of all the items in the list which are not in the current language context?
Thanks a lot in advance!
Dec 13, 2023, 12:01 AM
You would need to change the
filter
on your reference field. What does that code currently look like?
Dec 13, 2023, 12:10 AM
Hey
user M
, thanks for responding!!

queries.ts
export const homePageQuery = groq`
  *[_type == "home" && language == $language][0]{
    _id,
    overview,
    featuredEvents[]->{
      _type,
      coverImage,
      overview,
      "slug": slug.current,
      tags,
      title,
      language,
    },
    title,
    language,
    "translations": *[
      _type == "translation.metadata" && 
      ^._id in translations[].value._ref
    ][0].translations[]{
      // and spread the "value" of each reference to the root level
      ...(value->{
        language,
        title,
        featuredEvents[]->{
          "slug": slug.current,
          title,
          language,
        },
      })
    }
  }
`

from home.ts (Schema)
…
defineField({
      name: 'featuredEvents',
      title: 'Featured events',
      description:
        'These are the events that will appear first on your landing page.',
      type: 'array',
      of: [
        defineArrayMember({
          type: 'reference',
          to: [{ type: 'event' }],
        }),
      ],
    }),
…
Dec 13, 2023, 1:27 AM
user M
EDIT: I could resolve by filtering like so:
defineField({
      name: 'featuredEvents',
      title: 'Featured events',
      description:
        'These are the events that will appear first on your landing page.',
      type: 'array',
      of: [
        defineArrayMember({
          type: 'reference',
          to: [{ type: 'event' }],
          options: {
            filter: ({ document }) => {
              return {
                filter: '_type == "event" && language == $language',
                params: { language: document.language },
              }
            },
          },
        }),
      ],
    }),
Dec 13, 2023, 2:06 AM
Nailed it!
Dec 13, 2023, 4:58 PM

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?