How to set slug source to object's own title field in Sanity array?
When you have a slug field nested inside an object (like your headingBlock within an array), the source option needs to reference the field relative to that object's context, not the document level.
The key is using the parent parameter in the source function. Instead of:
source: 'title'You need:
source: (doc, { parent }) => parent.titleHere's how this works in your case:
{
name: 'headingBlock',
type: 'object',
fields: [
{
name: 'title',
type: 'string',
title: 'Title'
},
{
name: 'slug',
type: 'slug',
options: {
source: (doc, { parent }) => parent.title,
maxLength: 96
}
}
]
}The issue you're experiencing is that when a slug field is inside a nested object or array item, it's looking for the source field at the document root level by default. By using the function form of the source option, you get access to both doc (the entire document) and parent (the immediate parent object containing this slug field).
So parent.title refers to the title field within the same headingBlock object, rather than trying to find a title at the document root level (which would be the page document's title string).
This is a common gotcha when working with nested structures in Sanity schemas, and the parent accessor is specifically designed to solve this problem! I found a similar case in the Sanity community answers where someone had the exact same issue with an event object nested in an array, and using parent.eventName solved it.
Show original thread8 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.