How to set default value for string type options list in Sanity?

6 replies
Last updated: Aug 12, 2021
Would someone happen to know how to set the default value for the ‘string’ type ‘options’ list. I’ve moved the initialValue to multiple places, outside of the options, and into the initialValue object before the fields or after.
AI Update

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:

  1. Don't put initialValue inside the options object - it won't work there
  2. Make sure the value matches exactly - if your option has value: 'left', your initialValue should be 'left' (not 'Left' or the title)
  3. 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 thread
6 replies
put the
invitialValue
outside of
options
and you should be good
user Y
This is what I have also tried, which I believe is what you mean. This was not working for me.
user Y
I have that working now, I refreshed my IDE and re-ran the environment. Not sure why it wasn’t taking. Thank you.
user Y
I have that working now, I refreshed my IDE and re-ran the environment. Not sure why it wasn’t taking. Thank you.
Aha - glad you got it working!
user Y
I have that working now, I refreshed my IDE and re-ran the environment. Not sure why it wasn’t taking. Thank you.

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?