Like what we’re doing? Star us on GitHub!

Duplicate file from collection to collection

quornik
12 months ago
1 1

I'm trying to grasp around the idea of hooks.

PROBLEM

I need to create a hook that allows Admin to duplicate file after it has been reviewed to another collection, and delate the one he has reviewed.
Is there a tutorial or documentation on how to e.g. execute the CREATE operation on another collection with the use of data from currently edited file?

IDEA

And Is there a way to execute PUT, DELATE, FIND and other operations directly on Mongo with FETCH, inside hook?
Would appiciate some discussion or help.

  • denolfe
    Payload Team
    12 months ago

    Hey @quornik, this is definitely possible by combining the use of a beforeChange hook and the local API operations.

    Here is an example of how it can be done:

    import { CollectionBeforeChangeHook, CollectionConfig } from 'payload/types'
    
    const performOperationIfReviewed: CollectionBeforeChangeHook = async ({
      data, // incoming data to update or create with
      req, // full express request
      operation, // name of the operation ie. 'create', 'update'
      originalDoc, // original document
    }) => {
      if (
        req?.user?.collection === 'admins' && // Admins collection only
        operation === 'update' && // Only on update operations
        !originalDoc.reviewed && data.reviewed // Transitioning from not reviewed to reviewed
      ) {
        await req.payload.create({
          collection: 'collection-after-reviewed',
          data,
        })
      }
    }
    
    export const Pages: CollectionConfig = {
      slug: 'pages',
      hooks: {
        beforeChange: [performOperationIfReviewed],
      },
      fields: [
        {
          name: 'reviewFile',
          type: 'relationship',
          relationTo: 'media',
        },
        {
          name: 'reviewed',
          type: 'checkbox',
        }
      ],
    }

    Hopefully, that gets you going in the right direction. Let me know if you have any additional questions đź‘Ť

Open the post
Continue the discussion in GitHub
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More