How to set default value for string type options list in Sanity?
I feel your pain! Setting initialValue for a string field with an options list can be a bit tricky. The key is that initialValue should be placed at the same level as name, type, and options in your field definition, and it should be set to the value (not the title) from your options list.
Here's the correct syntax:
defineField({
name: 'myField',
title: 'My Field',
type: 'string',
initialValue: 'optionValue', // The value from your options list
options: {
list: [
{ title: 'Option One', value: 'optionValue' },
{ title: 'Option Two', value: 'anotherValue' }
]
}
})If you're using the simpler array format for options (just strings), it looks like this:
defineField({
name: 'myField',
title: 'My Field',
type: 'string',
initialValue: 'option1',
options: {
list: ['option1', 'option2', 'option3']
}
})Common mistakes to avoid:
- Don't put
initialValueinside theoptionsobject - it won't work there - Make sure the value matches exactly - if your option has
value: 'left', your initialValue should be'left'(not'Left'or the title) - For arrays of objects with options, the structure is different - you'd set it like
initialValue: [{ _type: 'yourType', yourField: 'value' }]
According to the Sanity documentation on initial value templates and the string field type docs, this field-level initialValue approach works for all new documents of that schema type. If you need more complex conditional defaults based on user context or parameters, you might want to look into Initial Value Templates configured in your sanity.config.ts file instead.
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.