- I have a Blog collection, and a Users collection.
- A blog can have one 'author', that is a relationship field, with
relationTo
the name of the Users collection:
users
.
- How can I autofill this value to be the currently logged in
user
on the admin panel, when creating the Blog?
This plugin has the code you're looking for, but it's for v2
https://github.com/boomworks/payload-plugin-author-fieldsThanks for this, i'l have a look
it is a
beforeChange
type of hook
const anotherHook: CollectionBeforeChangeHook<Blog> = async ({ data, req, operation }) => {
if (
operation === 'update' &&
data !== undefined &&
req.user !== undefined &&
req.user !== null
) {
data['author'] = {
relationTo: 'users',
value: req.user.id,
}
}
return data;
}
I tried to do something similar, but I get this error:
'relationTo' does not exist in type 'User'.
OK, it worked
export const validateAuthor: CollectionBeforeChangeHook<Blog> = async ({ data, req, operation }) => {
if (
operation === 'update' &&
data !== undefined &&
!data.author &&
req.user !== undefined &&
req.user !== null
) {
data.author = req.user.id
return data;
}
}
but I wanted to make it a FieldHook
is that not possible??
right now this is at the collections level
Star
Discord
online
Get dedicated engineering support directly from the Payload team.