I was trying to implement the slug field type feature using the directus 11.7.2 version and found that it could not be added directly and needed to be configured to flow, but ran into some problems. After configuring it and going to create a test product, it prompts The following fields have invalid values:Slug: Value can’t be null. can anyone help me with this or where do I go to find this configuration documentation, thanks.
Code:module.exports = async function(data) {
console.log(‘— Run Script START —’);
// 调试: 打印传入的整个 data 对象
// console.log(‘Input data object:’, JSON.stringify(data, null, 2));
if (!data || !data.$trigger || typeof data.$trigger.payload !== ‘object’ || data.$trigger.payload === null) {
console.error(‘Flow Script Error: $trigger.payload is missing or not an object.’);
throw new Error(‘Critical: $trigger.payload is invalid in Run Script.’);
}
const originalPayload = data.$trigger.payload;
const name = originalPayload.name; // name 字段现在是必填的,理论上不应为空或null
console.log(‘Original name from payload:’, name);
function slugify(text) {
if (typeof text !== ‘string’ || text.trim() === ‘’) {
console.warn(‘Slugify: Input name was empty or not a string. Resulting slug will be empty.’);
return ‘’;
}
let slug = text.toLowerCase()
.trim()
.replace(/\s+/g, ‘-’)
.replace(/[^\w-]+/g, ‘’)
.replace(/–+/g, ‘-’)
.replace(/^-+|-+$/g, ‘’);
console.log(Slugify: input="${text}", output="${slug}"
);
return slug;
}
let generatedSlug = slugify(name);
// 关键的检查和处理:如果生成的 slug 是空字符串
if (generatedSlug === ‘’) {
console.error(‘Generated slug is an empty string. Original name might be invalid for slug generation or was empty (even if required). Name:’, name);
// 策略1:抛出错误,阻止 Flow 继续,这将使 Directus 的保存操作失败,
// 但错误信息会更明确地指向 slug 生成问题,而不是简单的 “Value can’t be null”。
throw new Error(Failed to generate a valid slug from name: "${name}". Slug cannot be empty.
);
// 策略2 (仅用于极端调试,不推荐用于生产):赋一个确保非空的默认值
// generatedSlug = 'default-slug-' + Date.now();
// console.warn('Generated slug was empty, assigned a default temporary slug:', generatedSlug);
}
const newPayload = {
…originalPayload,
slug: generatedSlug
};
console.log(‘Run Script: Returning new payload:’, JSON.stringify(newPayload, null, 2));
console.log(‘— Run Script END —’);
return newPayload;
};