Is there a way to reference a top level field for preview?

6 replies
Last updated: Feb 3, 2021
Is there a way to reference a top level field for preview? I am trying to create an image block, and this is my code:
export default {
  name: 'imageObject',
  title: 'Image',
  type: 'image',
  fields: [
    { name: 'caption',
      type: 'simpleBlockContent',
      title: 'Caption',
      options: {
        isHighlighted: true
      }
    }
  ],
  options: {
    hotspot: true
  },
  preview: {
    select: {
      title: 'caption',
      media: 'imageObject'
    }
  }
}
The media for preview is returning nothing.
AI Update

I can see the issue in your code! When you want to reference the image field itself (which is the top-level field of your imageObject type), you should use asset to reference the image asset, not the schema type name.

In your current code, you have:

preview: {
  select: {
    title: 'caption',
    media: 'imageObject'  // This is incorrect
  }
}

The problem is that imageObject is the name of your schema type, not a field path. Since your type extends image (by setting type: 'image'), the actual image data is stored at the root level, and you need to reference the asset field specifically.

Here's the corrected version:

export default {
  name: 'imageObject',
  title: 'Image',
  type: 'image',
  fields: [
    { 
      name: 'caption',
      type: 'simpleBlockContent',
      title: 'Caption',
      options: {
        isHighlighted: true
      }
    }
  ],
  options: {
    hotspot: true
  },
  preview: {
    select: {
      title: 'caption',
      media: 'asset'  // Reference the image asset directly
    }
  }
}

According to the preview configuration documentation, when your type extends image, the asset field contains the reference to the image asset that the preview system needs to display the thumbnail. This should now properly show your image in the preview!

If I'm remembering correctly, the preview field is for documents and so you'd define it on documents that use the
imageObject
, not the imageObject itself.
previews also work on non-documents! eg if that type is being used in an array πŸ˜„
this should work:

preview: {
    select: {
      media: 'asset'
    }
  }
(asset is a key created for every image)
user B
that worked! Thanks so much!
Is that in the documentation?
youre welcome πŸ˜ƒ not sure, i think i just found it by trial and error

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.

Was this answer helpful?