How to programmatically populate fields array using GROQ query data?
I understand what you're trying to do, but unfortunately Sanity schemas must be static and cannot be dynamically generated at runtime based on data. The fields array in a schema definition needs to be defined when the Studio is built/loaded, not dynamically created per document.
Here's why and what alternatives you have:
Why Schemas Must Be Static
Sanity Studio needs to know the complete schema structure upfront to:
- Generate the editing interface
- Provide proper validation
- Enable GROQ queries to work correctly
- Support TypeScript type generation
You're correct that initialValue only sets the values of existing fields - it doesn't create new fields. And while references link to other documents, they don't dynamically alter the schema structure itself.
Alternative Approaches
Depending on what you're trying to accomplish, here are some solutions:
1. Use Conditional Fields
If you need fields to appear/disappear based on document data, use the hidden property:
defineField({
name: 'conditionalField',
type: 'string',
hidden: ({document}) => document?.someField !== 'specificValue'
})2. Use Objects or Arrays for Flexible Structure
For truly dynamic data structures, use an array of objects where users can add different field combinations:
defineField({
name: 'dynamicContent',
type: 'array',
of: [
{type: 'textBlock'},
{type: 'imageBlock'},
{type: 'customBlock'}
]
})3. Use Initial Value Templates for Dynamic Defaults
While you can't create fields dynamically, you can use Initial Value Templates to fetch data from other documents and populate field values when creating new documents:
{
id: 'document-from-template',
title: 'New Document',
schemaType: 'myType',
value: async (params, context) => {
const client = context.getClient({apiVersion: '2024-11-01'})
const sourceData = await client.fetch(
`*[_type == "source" && _id == $id][0]`,
{id: params.sourceId}
)
return {
field1: sourceData.someValue,
field2: sourceData.anotherValue
// These fields must already exist in your schema
}
}
}4. Use a Key-Value Pattern
For truly arbitrary data, use an array of key-value pairs:
defineField({
name: 'metadata',
type: 'array',
of: [{
type: 'object',
fields: [
{name: 'key', type: 'string'},
{name: 'value', type: 'string'}
]
}]
})5. Multiple Schemas Based on Context
If you need completely different field sets, create separate document types and use Initial Value Templates to guide users to the right one based on context.
If you can share more about your specific use case (what kind of data you're trying to pull and why you need it to generate fields), I can suggest a more tailored approach!
Show original thread18 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.