I have a product collection and i want to add a article number field.
I want the article number to be autogenerated and unique how could one go about to achieve this.
i.e 1001, ....1023., 1039 etc.
Use a field or collection hook to set a random number in the before validate or something like that
Hi! thank you for replying that was my initial thought but i need the article number to be "aware" of the collection i,e the count and it should be unique.
i would prefare i increased linearly aswell instead of a random num.
Have you tried inside the field hook for a number when the operation is 'create' using the local payload api to query the product document with the highest number currently set and adding 1 to it?
Alternatively you could query the total number of products and set the field to that + some initial number (1000 in your case).
Hey
@966272641260462121did you try this approach above? Do you still need help here? Just let us know and we'll work to get you an answer.
Hi, thank you for reaching out!
I have not tried it yet will do that tomorrow <t:1689231420:D> and let you know how it goes.
Autogenerate field content/ generate onsave
Hi
@364562745447940099&
@477521743842639884!
thank you for your replies.
here is what i tried.
import payload from 'payload'
import type { BeforeValidateHook } from 'payload/dist/collections/config/types'
import type { Product } from '../payload-types'
export const createArticleNumber: BeforeValidateHook<Product> = async ({ data, operation }) => {
if (operation === 'create') {
const products = await payload.find({
collection: 'product',
sort: '-articleNumber',
})
const productLength = products.totalDocs
if (productLength > 0) {
const previousArtNumber = products.docs[0].articleNumber.slice(4)
const newArtNumber = parseInt(previousArtNumber) + 1
return {
...data,
articleNumber: `Art-${newArtNumber}`,
}
}
return {
...data,
articleNumber: 'Art-1000',
}
}
}
I do have some follow up questions. i do not want the user to be able to manually update this field it should be disabled how do i achieve this?
Thanks alot!
Glad we got this sorted out! We're around if you need anything else.
Star
Discord
online
Get dedicated engineering support directly from the Payload team.