Like what we’re doing? Star us on GitHub!

How to add an automatic slug base on the title for a collection content?

johnmadrigal_
2 months ago
3

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"?

  • jesschow
    Payload Team
    2 months ago

    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);
      }
    };
  • Adroit
    last week

    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?

  • jesschow
    Payload Team
    last week

    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.

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More