Collection BeforeChange Hook - acess to auto-generated ID

default discord avatar
dawidmachonlast year
1 1

Hi,
I would ask if there is a smart way to access payload generated ID for collection in CollectionBeforeChangeHook?

Because right now, imagine the situation:

  • Collection Users has relation to collection BankAccount and in opposite way relation also exist. It is one to one always.
Users{
 userId: <payloadGenerated>
 bankAccountId: <idFromBankCollection>
}

BankAccount{
 bankAccoutnId: <payloadGenerated>
 owner: <idFromUserCollection>
}

For that case, I need two hooks:

  • CollectionBeforeChange on Users to create as local API BankAccount document and populate in Users bankAccountId.
  • CollectionAfterChange on Users to find and update as local API BankAccount document with userId.

That is because in CollectionBeforeChangeHook there is no pre-generated access to ID for not created yet User document. So is there a way to do it in a smarter way? Write own generation for ID on Users, and then use just one hook? But then I need own validations for checking if id is already existing?

Maybe someone has better idea how to proceed with such cases? Or should I avoid bi-directional relations, and simple embedding them on users?

  • Selected Answer
    discord user avatar
    jacobsfletch
    last year

    @dawidmachon you're right in that if the operation is create, there is not yet an ID to use. Your solution looks fine to me, does it work? Just to sum it up:

    1. Before a user is created, create a bank account and attach the bankAccountId to the user
    2. After a user is created, lookup their bank account and update the owner with their userId

    This will work for that initial connection but updates on either end of the relationship will also need to be wired in—and this may lead to infinite loops. There are ways around this, like maintaining a hidden skipHooks field on the collection, I've done something similar to this in our Stripe plugin. Others have run into this same need, though, and there's a community-supported plugin if you want to check it out: https://github.com/TimHal/pcms-backpop. I have not tested this myself but it might work for you 👍

    1 reply
  • default discord avatar
    dawidmachonlast year

    great answer. Thanks a lot for your response! Great warning for infinite loops.
    It's working, but I was curious if there is a 'smarter' way to do this. ;) Thanks for plugin!

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.