How to Use the Title String of the HeadingBlock As the Slug Source

8 replies
Last updated: Apr 29, 2021
I have a "page" document which contains both a "title" string and an array of objects, one of which I'm calling "headingBlock". The object also has a "title" string and a slug, and I want to use the "title" string of the object as the slug source. But I can only get it to use the document title string as source, not the title string of the "headingBlock" object that the slug is a part of (sorry for the confusing description). Any idea what to set the slug source to?
Apr 23, 2021, 7:49 AM
I see... I tested now and confirm the behavior you're saying. If I have two fields in the parent document called 'heading' and 'heading2', then the slug generation button in the 'heading2' object would get the 'title' string from the 'heading' object.
Is there no way around this behavior? If not, isn't this really a bug? When creating an object, the functionality of that object shouldn't be concerned about what name it is given when used. And in my case it's used in an array, so it cannot know what index number it has or if there are other objects of the same type in the array.
Apr 23, 2021, 8:50 PM
I definitely see your point there. An object should be able to operate without any awareness of what it’s contained within. I wonder if there’s a way you can dynamically set it so that you can sort of avoid this?
That said, I think these are valid points and you should share them in the
ideas-and-feedback channel or open up an issue on Github .
Apr 24, 2021, 4:27 PM
options.source
can be a function. Does this achieve what you’re after?

{
  name: 'slug',
  title: 'Slug',
  type: 'slug',
  options: {
    source: (_, { parent: { title } }) => title,
    maxLength: 96,
  },
},
Apr 27, 2021, 8:08 PM
Ah, so awesome! Worked like a charm! Can you elaborate a little on what that statement actually does?
Apr 28, 2021, 7:45 AM
Great! Yes, sorry I didn’t to start with. As a function, slug can take two parameters :
doc
and
options
. We don’t need
doc
in this case so convention is to use an underscore to represent it.
{ parent: { title } }
is destructuring `options`; the function could just as well be written:

source: (doc, options) => {
  const { parent } = options
  const { title } = parent
  return title
}
or


source: function(doc, options) {
  return options.parent.title
}

Apr 28, 2021, 1:39 PM
user A
thank you so much!
Apr 28, 2021, 4:36 PM
No problem!
Apr 28, 2021, 4:38 PM
Thank you for the help! 🙂
Apr 29, 2021, 5:30 AM

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?