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.

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

    2 replies
  • 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
    palak-convivity2 months ago

    same question?
    is it possible to show the users name on top of the collection where we have createdat and updatedat?

  • 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 dedicated engineering support directly from the Payload team.