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

default discord avatar
Stupidismlast year
4 2

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

  • Selected Answer
    discord user avatar
    denolfe
    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
    Stupidismlast year

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

  • default discord avatar
    xin-zelast year

    same request

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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