How to add audit info like createdBy and updatedBy? (similar to createdAt and updatedAt)

default discord avatar
Stupidism
last year
4 2

We want to record info like who created/update the doc
image

  • discord user avatar
    denolfe
    Payload Team
    last year

    Yes, this can be done w/ hooks and access control. Here is an example collection:

    const Posts: CollectionConfig = {
      slug: 'posts',
      hooks: {
        beforeChange: [
          ({ req, operation, data }) => {
            if (req.user) {
              if (operation === 'create') {
                data.updatedBy = req.user.id;
                data.createdBy = req.user.id;
              } else if (operation === 'update') {
                data.updatedBy = req.user.id;
              }
              return data;
            }
          },
        ],
      },
      fields: [
        {
          name: 'createdBy',
          type: 'relationship',
          relationTo: 'users',
          access: {
            update: () => false,
          },
          admin: {
            readOnly: true,
            position: 'sidebar',
            condition: (data) => !!data?.createdBy,
          },
        },
        {
          name: 'createdBy',
          type: 'relationship',
          relationTo: 'users',
          access: {
            update: () => false,
          },
          admin: {
            readOnly: true,
            position: 'sidebar',
            condition: (data) => !!data?.createdBy,
          },
        },
        // Other fields
      ],
    };
    export default Posts;

    This will now show in the admin sidebar

    image

    1 reply
  • default discord avatar
    Stupidism
    last year

    Is it possible to add these two fields' information in the area of the screenshot I took above?

  • default discord avatar
    zhounewz
    last year

    same request

Open the post
Continue the discussion in GitHub
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.