Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Autofill relationship field value

default discord avatar
lzyaclast year
2

- 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?



  • default discord avatar
    tyteen4a03last year

    This plugin has the code you're looking for, but it's for v2

    https://github.com/boomworks/payload-plugin-author-fields
  • default discord avatar
    lzyaclast year

    Thanks 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 on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.