Creating articles on cms directus (version 11.3.5) that I want to use for a blog.
I’ve found the documentation about creating slugs automatically and the discussions on github
I’ve used it on the title field on my articles, with the following code :
module.exports = async function (data) {
// Index data to get the string you want to slugify
// Assign it to the "text" var below.
const text = data.$trigger.payload.title;
const slug = text
.toLowerCase()
.trim()
.replace(/[^ws-]/g, '')
.replace(/[s_-]+/g, '-')
.replace(/^-+|-+$/g, '');
return {
...data.$trigger.payload, slug
}
};
I’ve used it on the scope item.create
and item.update
, on my articles_translations
table which holds the translated data of each article.
I’ve created the flow as precised and got no errors. I don’t understand now how I can check it worked ? In which field will it be stored ?
I had to create a slug field on the table article_translation
for it to work.
I’ve used this snippet instead :
const slugify = text =>
text
.toString()
.normalize('NFD')
.replace(/[u0300-u036f]/g, '')
.toLowerCase()
.trim()
.replace(/s+/g, '-')
.replace(/[^w-]+/g, '')
.replace(/--+/g, '-');
module.exports = async function(data) {
// if title not passed
if (data.$trigger.payload.title === undefined) return data.$trigger.payload;
// if user entered slug themselves...
if (data.$trigger.payload.slug !== undefined) return data.$trigger.payload;
/// generate slug
const slug = slugify(data.$trigger.payload.title);
return {...data.$trigger.payload, slug};
}
from this website.
To create the slug on update, you have to update the title – else it’s not part of the payload when updating. If you forget it, with this snippet it won’t crash (it does with the first one on update)
so:
- create the slug field (just a regular input field) for it to be filled automatically with the script
- use the script in the flows as stated here