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.

Add/Modify a field in `afterChange` collection Hook

default discord avatar
loaialshareelast year
3

Hello,



I am trying to add/modify a field in

afterChange

collection hook. Can anyone advise me how I can achieve that? I tried doing:



hooks: {
    afterChange: [
      async (data) => {

        data.doc.new_field = 'test'        // adding a new field => doesn't work
        data.doc.existing_field = 'test'   // works locally but value is not reflected in db 
        
        console.log(data);
      },
    ],
  },

This might seem as a straight forward question, but I don't find a way for it.

  • default discord avatar
    notchrlast year
    @688635079450296388

    Does it have to be done in the afterChange hook?



    Also, I notice you're not returning the doc in the afterChange hook

  • default discord avatar
    loaialshareelast year
    @1049775120559898725

    Thank you for your insight! It seems that I need to add the

    new_field

    to the collection fields first to be able to reflect on both db and API from the hooks. It appears that it doesn't create a field on the fly.



    For the existing fields (like the ones attached with the image upload field once linked with Media collection by default), I guess modifying them is not possible.

  • - Adding fields on the fly is not possible. Payload is code first, so adding the field to your collection fields is the way to go


    - You can modify fields, but you are likely looking for a beforeChange hook, afterChange is too late, the data has already been saved in the DB

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.