I have a beforeCreate lifecycle hook where I want to change a field based on some component data on a collection. However, when debugging the event data, I only see the “__pivot” object that contains the id, component_type and field inside. I was curious if it is possible to populate the component data during the event so Icana ctually access the data inside?
This topic has been created from a Discord post (1295693969019244606) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord
You want to use afterCreate.
Since before create has no information about the data in the fields
Hm, are you sure? This worked for me
const companySchema = object({
name: string().min(1, 'form.errors.minLength,${min}'),
slug: string().required('form.errors.required').min(1),
website: string().required('form.errors.required').url().min(1),
phone: string().required('form.errors.required').min(1),
email: string().required('form.errors.required').email().min(1),
description: string().required('form.errors.required').min(1),
thumbnail: string().required('form.errors.required').min(1),
address: object({
address: string().required('form.errors.required').min(1),
zipCode: string().required('form.errors.required').min(1),
city: string().required('form.errors.required').min(1),
}),
})
export default {
async beforeCreate(event: Event) {
const ctx = strapi.requestContext.get()!
await validate(companySchema, ctx.request.body)
},
}
// validate.js
export async function validate<T extends Schema>(schema: T, data: any) {
const errors = {} as Partial<{
[K in T['__outputType']]: string[]
}>
try {
return await schema.validate(data, { abortEarly: false })
} catch (e) {
if (e instanceof ValidationError) {
const { inner } = e
for (const error of inner) {
set(errors, error.path, error.errors)
}
}
throw errors
}
}
If it works then I was wrong
I probebly mixed someting up in my head
I dont know about that haha, but found somewhere in the docs that I can use strapi.requestContext.get()