How to get Initial Values from a Media Object
Yes, you can definitely set initial values for fields within an array of objects like your media array! There are a couple of approaches depending on what you want to achieve:
Setting Initial Values for Boolean Fields
For the boolean fields in your Video object (autoplay and controls), you can set default values directly in the field definition using the initialValue property:
{
title: "Media",
name: "media",
type: "array",
of: [
{
title: "Image",
type: "image",
},
{
title: "Video",
type: "object",
fields: [
{
title: "Video Url",
name: "url",
type: "url",
},
{
title: "Autoplay",
name: "autoplay",
type: "boolean",
initialValue: false // Default value
},
{
title: "Controls",
name: "controls",
type: "boolean",
initialValue: true // Default value
},
],
},
],
}This will set default values whenever a new Video object is added to the array.
Using Initial Value Templates for More Complex Scenarios
If you need more sophisticated initialization (like setting values based on context, user information, or external data), you can use Initial Value Templates. These are configured in your sanity.config.ts file and allow you to:
- Set dynamic values based on parameters
- Access current user information
- Fetch data from external APIs
- Create multiple preset options for the same schema type
// sanity.config.ts
export default defineConfig({
document: {
newDocumentOptions: (prev, context) => {
return [
...prev,
{
id: 'video-with-defaults',
title: 'Video (autoplay enabled)',
schemaType: 'video',
value: {
autoplay: true,
controls: false
}
}
]
}
}
})The field-level initialValue approach is usually the simplest solution for setting defaults on boolean fields within array items, and it works great for your use case!
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.