I am trying to use a hook for generating slug based on title
{
name: 'title',
required: true,
type: 'text',
localized: true,
},
{
name: 'slug',
required: true,
type: 'text',
unique: true,
localized: true,
hooks: {
beforeValidate: [slugify('title')],
},
},
but I get this error:
Field "slug" > "value" does not match any of the allowed types
I want to generate the slug from the title. I took a look at the website on GitHub (
https://github.com/payloadcms/website-cms/blob/b130b43cc1cf7a0ac1ba4c71ba7db90627f7a444/src/fields/slug.ts#L7) and that is how I got the hook but I dont want to create another field called slug and etc, I just want to use it inside the collection file
is it because you don't want the field to show up in the admin UI?
i.e. = you just want the data to be in the API response, and not be editable
to do that, you can set
admin.disabled
to
true
on your slug field
and it will be hidden in admin UI
@jmikrut yes, the idea is to auto generate the slug value from the title automatically when post is saved
but the issue is Field "slug" > "value" does not match any of the allowed types error
that means you don't have your field config for the
slug
field correct
can you copy / paste your
slug
field config here?
hum, I am not sure, I added it as a text field
{
name: 'slug',
required: true,
type: 'text',
unique: true,
localized: true,
hooks: {
beforeValidate: [slugify('title')],
},
},
slugify
https://www.npmjs.com/package/slugifyis this library I want to use
to convert the title
the error is because you are not writing your
beforeValidate
hook properly
in that snippet, you're
callingthe function, which will likely return a string. The
beforeValidate
property can only accept an array of functions
so you need to write your beforeValidate hook itself as a function, and not call it
oh I see, thank you
I will give it a shot tomorrow morning
@jmikrut I managed to get this working and use title automatically as a slug
Thank you for your help
@generator101 could you kindly post your solution here? I'm also having issues working dynamically between different field selections.
sure
@KasparTr here you go
{
name: 'slug',
type: 'text',
unique: true,
localized: true,
index: true,
admin: {
readOnly: true
},
hooks: {
beforeValidate: [
({ req: { payload }, data }) => {
if (payload) {
return slugify(data.title)
}
},
],
},
},
I used this library
https://www.npmjs.com/package/slugify
to convert title to slug
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.