Slug from two fields (moved from Community)

is it possible to create a slug from two different fields (first_name + last_name)?


Hi @elia,

Not out of the box, but you can use the Computed Fields plugin for this: Computed Fields - Plugins — DatoCMS


slug Field Setup

We turn off the “Reference field” because we’ll do it in code instead:

In the Presentation tab, we assign that field to the Computed Fields plugin and give it a simple slugification function:

You can copy and paste this code or modify it as you need:

// From
const slugify = (str) => {
  return String(str)
    .normalize('NFKD') // split accented characters into their base characters and diacritical marks
    .replace(/[\u0300-\u036f]/g, '') // remove all the accents, which happen to be all in the \u03xx UNICODE block.
    .trim() // trim leading or trailing whitespace
    .toLowerCase() // convert to lowercase
    .replace(/[^a-z0-9 -]/g, '') // remove non-alphanumeric characters
    .replace(/\s+/g, '-') // replace spaces with hyphens
    .replace(/-+/g, '-'); // remove consecutive hyphens

// Concat first name + last name and then slugify
return slugify(`${first_name ?? ''}${last_name ? '-' + last_name : ''}`)

If you need more powerful slugification, you can fork that Computed Fields plugin and add a third-party lib like slugify. But for simpler use cases, that code above should suffice.

1 Like

Wow @roger thanks for that, it works perfectly!!
Just one more question, is it possibile to check that every slug will be unique, and in case add a number or something at the end?

@elia In the validations tab, you can check the “Unique field” box:

I think it might be a little difficult to programatically add a number to the end of non-unique slugs, because you’d have to fetch all existing slugs of that model first, count the numbers, and try to add 1. But I suppose you could do that, if you really wanted to, by forking that computed fields plugin and fetching records from your model using our CMA or CDA APIs.

It might be easier to just add another optional text field, instead, and add that to the computed fields output:

And the only part of the code I had to change was line 14, adding the slug_suffix field too:

return slugify(`${first_name ?? ''}${last_name ? '-' + last_name : ''}${slug_suffix ? '-' + slug_suffix : ''}`)

Your editors would have to manually try tweaking the suffix until they find something unique, but I think that would be better for SEO anyway, since you can use meaningful words to describe the article instead of just appending random numbers (that get confusing to both viewers and editors)