Files
anouma/fields/slug.ts
T

41 lines
1.0 KiB
TypeScript

import type { Field } from "payload";
function slugify(value: string): string {
return value
.toLowerCase()
.trim()
.replace(/ä/g, "ae")
.replace(/ö/g, "oe")
.replace(/ü/g, "ue")
.replace(/ß/g, "ss")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
/**
* A "Slug" field that auto-fills itself from `sourceField` (usually the
* title) whenever left empty, so the admin never has to think about URLs.
*/
export function slugField(sourceField = "title"): Field {
return {
name: "slug",
type: "text",
label: "URL-Kürzel",
unique: true,
index: true,
admin: {
position: "sidebar",
description: "Wird automatisch aus dem Titel erzeugt, kann aber angepasst werden.",
},
hooks: {
beforeValidate: [
({ value, data }) => {
if (value) return slugify(String(value));
const source = data?.[sourceField];
return typeof source === "string" ? slugify(source) : value;
},
],
},
};
}