For example I have News Collection and it has a content with the title "Content Sample".
Is it possible to have a automatic slug from its api that has a value "content-sample"?
Absolutely - you could achieve this with a field hook and a function to format your title to a slug.
For example:
{
name: 'slug',
type: 'text',
hooks: {
beforeValidate: [
formatSlug('title'),
],
},
}
const formatSlug = (): FieldHook => ({ value }) => {
const slugify = (val: string): string => val.replace(/ /g, '-').replace(/[^\w-]+/g, '').toLowerCase();
if (typeof value === 'string') {
return slugify(value);
}
};
I just tried this, thanks!
but i'm getting
Expected 0 arguments, but got 1
on formatSlug('title'). Is the type declaration for formatSlug correct?
Ah looking at it now the
formatSlug
function is incomplete, that part will slugify any value you manually type in but to automatically populate it with another field we need to add more:
const formatSlug = (fallback: string): FieldHook => ({ operation, data, originalDoc, value }) => {
const slugify = (val: string): string => val.replace(/ /g, '-').replace(/[^\w-]+/g, '').toLowerCase();
if (typeof value === 'string') {
return slugify(value);
}
if (operation === 'create') {
const fallbackData = data?.[fallback] || originalDoc?.[fallback];
if (fallbackData && typeof fallbackData === 'string') {
return slugify(fallbackData);
}
}
};
That will use the field you pass through but also allow you to manually enter a value (see screen recording) also this will take care of your error.
@jesschow it doesn't seem to be working with my
drafts
enabled.
On Publish, I get a required field validation error
On Save Draft, it generates the slug and saves the doc
This is my field
{
name: 'slug',
type: 'text',
required: true,
unique: true,
admin: {
position: 'sidebar',
readOnly: true,
},
hooks: {
beforeValidate: [formatSlug('title')],
},
},
Any quick tips on how I can make it work please? 😦
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.