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.

Duplicate file from collection to collection

default discord avatar
quornik3 years 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.

  • Selected Answer
    discord user avatar
    denolfe
    3 years 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 👍

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.