👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Customizing the selection of reference types in a document field in Sanity.io.

3 replies
Last updated: Aug 25, 2021
I have a document where one field is an array of references. This field can reference many different types, and the list that pops up when you click “Add” in the studio is becoming long. Is there anyway to customize the selection of type of reference to add to a list? Ideally we’d display them in a grid with a visual representation of each one. If the component doesn’t support different selections, any pointers on extension points or other building blocks we could use to create something would be appreciated 🙏
Aug 24, 2021, 6:00 AM
I was able to get something along these lines hacked together by using conditional fields (currently in beta ). However, I have to put all of the options inside of an object. For example, you have an array:
    {
      name: 'things',
      title: 'Things',
      type: 'array',
      of: [
        { type: 'referenceObject'}
      ]
    }
Then you create your referenceObject that conditionally shows a reference based off of the currently selected sibling string.

export default {
  name: 'referenceObject',
  title: 'Reference Object',
  type: 'object',
  fields: [
    {
      name: 'type',
      title: 'Type',
      type: 'string',
      options: {
        list: [
          { title: 'Movie', value: 'movie'},
          { title: 'Person', value: 'person'},
          { title: 'Screening', value: 'screening'}
        ]
      }
    },
    {
      name: 'movieReference',
      type: 'reference',
      to: [{ type: 'movie' }],
      hidden: ({ parent }) => parent?.type &&
        parent?.type == 'movie' ? false : true
    },
    {
      name: 'personReference',
      type: 'reference',
      to: [{ type: 'person'}],
      hidden: ({ parent }) => parent?.type &&
        parent?.type == 'person' ? false : true
    },
    {
      name: 'screeningReference',
      type: 'reference',
      to: [{ type: 'screening'}],
      hidden: ({ parent }) => parent?.type &&
        parent?.type == 'screening' ? false : true
    },
  ]
}
It could probably be polished up and made functional!
Aug 24, 2021, 10:28 PM
Interesting, thanks!
Aug 25, 2021, 5:53 AM
Interesting, thanks!
Aug 25, 2021, 5:53 AM

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?