Using initialValueTemplates to reference parent document fields
Good news! Yes, you can absolutely fetch the parent document's values within your initial value template. Your solution using context.getClient() is exactly the right approach.
Based on the official Initial Value Templates documentation, when you define a template in schema.templates, the value function receives two parameters:
params- containing any parameters you pass (like yourparentId)context- which includes helpful utilities likegetClient,currentUser,schema,dataset, andprojectId
Here's how to fetch parent document fields and use them in your new document:
// sanity.config.ts
import {defineConfig} from 'sanity'
export default defineConfig({
// ...rest of config
schema: {
templates: (prev, context) => [
...prev,
{
id: 'child-with-parent-specs',
title: 'Child Document',
schemaType: 'childDocument',
parameters: [{name: 'parentId', type: 'string'}],
value: async (params, context) => {
// Get a Sanity client from the context
const client = context.getClient({apiVersion: '2024-11-01'})
// Fetch the parent document with its specifications field
const parentDoc = await client.fetch(
`*[_id == $parentId][0]{
_id,
specifications
}`,
{parentId: params.parentId}
)
// Return initial values for the new document
return {
parent: {
_type: 'reference',
_ref: params.parentId
},
specifications: parentDoc?.specifications || []
}
}
}
]
}
})The key points:
- Make the
valuefunctionasyncso you can await the fetch operation - Use
context.getClient()to get a configured Sanity client - this is available in the context parameter - Query with GROQ to fetch exactly the fields you need from the parent document
- Handle reference arrays - if
specificationsis a ref array, the references will be copied as-is with their_refvalues intact
Your solution from the Sanity Answers thread demonstrates this perfectly! If you need to transform the references (like mapping them to a different structure), you can use .map() as you showed:
characteristics: category.characteristics.map((c: any) => ({
_type: 'partCharacteristic',
characteristic: {_type: 'reference', _ref: c._ref}
}))This pattern works great when combined with Structure Builder for creating contextual document creation flows where child documents inherit properties from their parent. Just use .initialValueTemplates() in your structure definition to specify which template should be used in that context, passing the necessary parameters like parentId.
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.