Conditional field with 3 choices in sibling momentType field
Based on your momentType field with three choices (image, video, and text), you can use conditional fields to show/hide related fields for each type. Here's how to implement it:
{
name: 'momentType',
type: 'string',
title: 'Moment Type',
options: {
list: [
{title: 'Image', value: 'image'},
{title: 'Video', value: 'video'},
{title: 'Text', value: 'text'}
]
}
},
// Image-specific fields
{
name: 'imageField',
type: 'image',
title: 'Image',
hidden: ({parent}) => parent?.momentType !== 'image'
},
// Video-specific fields
{
name: 'videoUrl',
type: 'url',
title: 'Video URL',
hidden: ({parent}) => parent?.momentType !== 'video'
},
// Text-specific fields
{
name: 'textContent',
type: 'text',
title: 'Text Content',
hidden: ({parent}) => parent?.momentType !== 'text'
}The key is using the hidden property with a callback function that receives parent as a parameter. The parent object contains the values of sibling fields in the same object or document. By checking parent?.momentType, you can show/hide fields based on the selected choice.
Important considerations:
- Validation: If you need any of these conditional fields to be required, you'll need conditional validation since hidden required fields still enforce validation:
{
name: 'imageField',
type: 'image',
hidden: ({parent}) => parent?.momentType !== 'image',
validation: (Rule) =>
Rule.custom((currentValue, {parent}) => {
return parent?.momentType === 'image' && !currentValue
? 'Image is required when moment type is image'
: true
})
}- Multiple related fields: You can have multiple fields for each type - just use the same conditional logic for all fields that should appear together.
For more details on conditional fields, check out the official documentation and this helpful guide on conditional fields in arrays.
Show original thread6 replies
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.