#Can we have a "slug" field?

5 messages · Page 1 of 1 (latest)

thorny crystal
#

Most CMS out there have some sort of concept of a "slug" for use in URLs where it's a URL friendly string (text field) that's auto-populated from the document title (replacing nonalphanumeric characters with a hyphen and lowercasing it) by default but can be changed by the editor as long as the resulting slug is unique, either within the whole system or at least within the content type (collection).

Is it possible to create such a field natively in Payload or would this require a custom field?

dull dawn
gentle oar
#

Yes you can use the beforeValidate hook @thorny crystal

thorny crystal
#

Two further questions...

  1. Is there a way to make the field value be "unique" and validated as such
  2. Is there a way to create a new API endpoint to easily retrieve single documents by their slug instead of ID?
inner moss
#

You can set unique: true on the field to ensure it's unique among other documents in the same collection. Then to query by slug, do something like this: where: { slug: { equals: 'test' } }