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

default discord avatar
Stupidism2 years ago
4 2

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

  • Selected Answer
    discord user avatar
    denolfe
    2 years ago

    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
    Stupidism2 years ago

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

  • default discord avatar
    blueMountain0072 years ago

    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.