Set initial value of reference field to current document in Sanity schema
Yes, you can absolutely set initial values from the current document when creating a referenced redirect document! The key is using parameterized Initial Value Templates defined in your schema.templates configuration.
Configuration in sanity.config.ts
Define your parameterized template in the schema.templates array in your Sanity config:
// sanity.config.ts
import {defineConfig} from 'sanity'
export default defineConfig({
// ...rest of config
schema: {
templates: (prev) => [
...prev,
{
id: 'redirect-from-document',
title: 'Create Redirect',
schemaType: 'redirect',
parameters: [
{name: 'sourceDocId', type: 'string'}
],
value: (params) => ({
sourceDocument: {
_type: 'reference',
_ref: params.sourceDocId
}
})
}
]
}
})Schema Definition
Your redirect schema might look like:
defineType({
name: 'redirect',
type: 'document',
fields: [
defineField({
name: 'sourceDocument',
type: 'reference',
to: [{type: 'page'}, {type: 'post'}] // whatever types you're redirecting from
}),
defineField({
name: 'targetUrl',
type: 'url'
})
]
})Using the Template in Structure Builder
To trigger this template from within a document's context, you can use the Structure Builder to pass the current document's ID as a parameter:
// structure.ts
export const structure = (S) =>
S.list()
.title('Content')
.items([
S.documentTypeListItem('page').child((pageId) =>
S.document()
.schemaType('page')
.documentId(pageId)
.views([
S.view.form(),
S.view.component(() => /* your custom view */).title('Redirects')
])
),
// ... other items
])Within a custom document action or view, you can create a new redirect using the template:
.initialValueTemplates([
S.initialValueTemplateItem('redirect-from-document', {sourceDocId: documentId})
])Async Values with Additional Data
If you need to fetch additional data from the parent document (not just the reference), you can make the value function async:
{
id: 'redirect-from-document',
title: 'Create Redirect',
schemaType: 'redirect',
parameters: [
{name: 'sourceDocId', type: 'string'}
],
value: async (params, context) => {
const client = context.getClient({apiVersion: '2024-11-01'})
const sourceDoc = await client.fetch(
`*[_id == $id][0]{_id, slug}`,
{id: params.sourceDocId}
)
return {
sourceDocument: {_type: 'reference', _ref: params.sourceDocId},
// Pre-populate other fields based on the source doc
oldSlug: sourceDoc?.slug?.current
}
}
}The context parameter provides access to getClient, currentUser, schema, dataset, and projectId, giving you full flexibility to build sophisticated initialization logic based on the parent document's data.
This approach ensures that when creating a redirect from a specific document's context, the reference is automatically populated, making the editorial workflow much smoother!
Show original thread14 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.