Hi guys, i'm currently working on building a blog using payload. I've just implemented a hook for formatting the title and setting it as a slug like so
export const formatSlug: FieldHook = async ({ value, data }) => {
return data?.title?.replace(/ /g, '-').toLowerCase() ?? value
}
{
name: 'slug',
type: 'text',
hooks: {
beforeChange: [formatSlug],
},
label: 'The slug is automatically generated from the title.',
admin: {
readOnly: true,
},
},
But this has the potential to create two slugs the same (if for whatever reason the title of the blog post is repeated) - Is there anyway to prevent his happening?
you can set "unique: true" on the field
I believe that should cover it to make sure that your slug is actually unique but i think it may be per collection and not global, not sure about that part
🤦‍♂️ didn't realise it was that simple
thanks a lot
Dw about it, theres lots of random small bits like this thats not easy to always find
It works perfectly too, so thank you!
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.