Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Using a reference field to generate a slug in Sanity Studio.

6 replies
Last updated: Apr 17, 2024
Hi! Is it possible to dereference something inside the studio? I have a document with a slug field, that I want to base on a different field in the document (a reference). I want to do something like this:
defineField({
    title: "Slug",
    name: "slug",
    type: "slug",
    options: {
        source: 'field_that_references_other_page',
        slugify: (input: string, schema, context) => {
           // .. use data from other_page chosen by context.parent.field_that_references_other_page
        }
Apr 17, 2024, 10:47 AM
export async function parentSlugify(_input_: any) {

const parentQuery = '*[_id == $id][0]'

const parentQueryParams = {

id: _input_.doc.parent?._ref || '',

}


const parent = await client.fetch(parentQuery, parentQueryParams)


const parentSlug = parent?.slug?.current ? parent.slug.current : ''

const pageSlug = _input_.doc.title.toLowerCase().replace(/\s+/g, '-').slice(0, 200)


if (!parentSlug) {

return slugify(pageSlug)

}

`return `${slugify(parentSlug)}/${slugify(pageSlug)}``

}

And then in your slug:


slugify: parentSlugify
Apr 17, 2024, 10:54 AM
You'd probably have to change around the parentQueryParams, but that should do the trick
Apr 17, 2024, 10:54 AM
Thank you so much! I was afraid calling
client.fetch
in the studio would cause some sort of crazy loop, but apparently it doesn’t haha. I’ll try this!
Apr 17, 2024, 10:55 AM
This (I believe), will only run once, when you click generate.
Apr 17, 2024, 10:56 AM
It works like a charm! Thank you Liam 🙂
Apr 17, 2024, 10:58 AM
For me sanity replaces the slash in my slug with a dash "/" to "-" and i cant seem to fix this issue. Any help?
Apr 17, 2024, 3:33 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?