Collection config allow me to overwrite payload ID implement, but can't define defaultValue
. Classic ID numbering is not an option to me, to prevent users discovering and playing with other entries, just changing ID.
Would like to fully customize using nanoID but any ID like, its totally fine. Is it possible?
Hey @didiraja,
I was surprised that defaultValue is not allowed for custom ID fields. As another workaround you could add it to the beforeValidate hook like this:
// in your collection:
hooks: {
beforeValidate: [({ data }) => {
if (!data.id) {
// replace with your own way to generate IDs
const customID = uuid()
return {...data, id: customID }
}
return data
}],
},
fields: [
{
name: 'id',
type: 'text',
admin: {
components: {
Field: () => null,
},
},
},
// ... rest of the fields
}]
@didiraja please mark this as answered if it solved your issue. If not, I'm curious what happened.
Thanks!
@DanRibbens worked flawlessly, thanks!
@DanRibbens This is how Payload reacts when I try to overwrite id object using defaultValue:
collection definition:
const Events: CollectionConfig = {
slug: 'events',
auth: false,
admin: {
useAsTitle: 'title',
},
fields: [
{
name: 'id',
type: 'text',
defaultValue: nanoid(),
required: true,
},
{
label: 'Título',
name: 'title',
type: 'text',
required: true,
},
terminal output:
[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node src/server.ts -- -I`
[12:12:19] ERROR (payload): There were 1 errors validating your Payload config
[12:12:19] ERROR (payload): 1: Collection "events" > Field "id" > "defaultValue" is not allowed
[nodemon] app crashed - waiting for file changes before starting..
defaultValue
kind of works in payload v3.
fields: [
{
name: 'id',
type: 'text',
required: true,
defaultValue: uuid,
hidden: true
}]
If we keep the id
hidden, it works on create page.
But on list page all entries get the same id.
It generates a new uuid which not does match any entry and clicking on any entry takes you to 404.
Following works as fix.
fields: [
{
name: 'id',
type: 'text',
required: true,
defaultValue: uuid,
admin: {
components: {
Field: undefined,
},
},
},
Star
Discord
online
Get dedicated engineering support directly from the Payload team.