Unlock seamless workflows and faster delivery with our latest releases- get the details

Issue with slug auto-generation in Sanity.io schema

4 replies
Last updated: Jun 20, 2023
Slug isn't auto-generating when clicking 'Generate' - code in thread
Jun 20, 2023, 6:35 PM

import {defineType, defineField} from 'sanity'

export default defineType({
  type: 'object',
  title: 'Swatch',
  name: 'swatch',
  fields: [
    defineField({
      title: 'Name',
      name: 'name',
      type: 'string',
      validation: (Rule) => Rule.required(),
    }),
    defineField({
      title: 'Handleized name',
      name: 'handle',
      type: 'slug',
      options: {
        source: 'name',
        disableArrayWarning: true,
      },
      description: "",
      validation: (Rule) => Rule.required(),
    }),
    defineField({
      title: 'Color',
      name: 'color',
      type: 'color',
      validation: (Rule) => Rule.required(),
    }),
  ],
  preview: {
    select: {
      title: 'name',
      subtitle: 'color.hex',
      media: 'color',
    },
    prepare({title, subtitle, media}) {
      return {
        title,
        subtitle,
        media: <div style={{backgroundColor: media.hex, width: '100%', height: '100%'}} />,
      }
    },
  },
})
Doesn't seem to be doing anything except from saving the document on click of generate.
Jun 20, 2023, 6:35 PM
Since this is part of an object, you may need to specify the full path (e.g., it looks like
swatch.name
, but you’ll want to check on your schema). I don’t know if this is the cause, but would be worth checking if that resolves this.
Jun 20, 2023, 6:41 PM
Just confirmed this. Your slugify function is looking for a
name
property at the top level of the document.
Jun 20, 2023, 6:44 PM
Thanks
user A
. That answers it, this is in an array as well.

source: (_, context) => context.parent.name,
This was the fix
🙂
Jun 20, 2023, 7:05 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?