Setting up a list view with conditional fields in Sanity.io.
I'd be happy to help you set up a list view with Conditional Fields! This is definitely doable, though it requires understanding how the Structure Builder and Conditional Fields work together.
Let me give you a comprehensive answer covering the most common scenarios:
Setting Up a Custom List View
First, you'll want to configure a custom structure in your sanity.config.ts:
import {structureTool} from 'sanity/structure'
import {structure} from './structure'
export default defineConfig({
// ... other config
plugins: [
structureTool({structure}),
// ... other plugins
],
})Then create your structure file (e.g., structure/index.ts):
import type {StructureResolver} from 'sanity/structure'
export const structure: StructureResolver = (S) =>
S.list()
.id('root')
.title('Content')
.items([
S.documentTypeListItem('yourDocType').title('Your Documents'),
// Add more list items as needed
])Conditional Fields in Your Schema
The Conditional Fields feature uses callback functions in your schema to show/hide fields based on document values:
{
name: 'contentType',
type: 'string',
options: {
list: ['image', 'video', 'text']
}
},
{
name: 'imageField',
type: 'image',
hidden: ({parent}) => parent?.contentType !== 'image'
},
{
name: 'videoField',
type: 'url',
hidden: ({parent}) => parent?.contentType !== 'video'
}Combining List Views with Conditional Fields
If you need to filter your list view based on documents that have certain conditional field configurations, you can use filtered document lists:
S.listItem()
.title('Documents with Images')
.child(
S.documentList()
.title('Image Content')
.filter('_type == "yourDocType" && contentType == "image"')
)Common Challenges
Validation with Hidden Fields: If you have required fields that are conditionally hidden, you'll need conditional validation:
validation: (Rule) =>
Rule.custom((currentValue, {parent}) => {
return parent?.contentType === 'image' && !currentValue
? 'Image is required when content type is image'
: true
})Arrays with Conditional Fields: When working with arrays of objects with conditional fields, the parent parameter in your callback refers to the array item object, not the document.
Feel free to share more details about your specific setup in your follow-up, and I can provide more targeted guidance!
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.