Using slug source from array child in Sanity
Yes, absolutely! You can use the slug source option with fields from a child object in an array. The key is using the parent parameter in the source function.
When you define a slug field inside an object type (especially one used in an array), you can access the parent object's fields using a function for the source option:
{
name: "contentBlock",
type: "object",
fields: [
{
name: "title",
type: "string",
},
{
name: "slug",
type: "slug",
options: {
source: (doc, { parent }) => parent?.title
}
}
]
}The naming can be a bit confusing here - parent actually refers to the immediate parent object (the current contentBlock in this case), not the top-level document. So parent.title gives you the title field from the same object where your slug lives.
This is particularly useful when you have an array of objects and want each item to generate its own slug based on its own fields:
{
name: "page",
type: "document",
fields: [
{
name: "content",
type: "array",
of: [{ type: "contentBlock" }]
}
]
}Each contentBlock in the array can now generate its slug from its own title field rather than trying to reference something at the document level.
This feature was added to Sanity back in 2019 and works great for creating slugs in nested structures. The parent parameter gives you exactly what you need to reference fields within the same object context.
Show original thread10 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.