Let's say i have two collections one is buses another is owner. Now when i am creating a bus it should trigger an owner creation as well. and this owner collection has two fields one is the name another one is buses which is relationship to buses. so now how can i achieve that ?
I think a
beforeChange
hook would work for that. Just check if the
operation
is
create
, then create a new document from the hook using payload's local api
i was thinking to use afterChange though. The problem here is the syntax. I am not kinda familier with it. Where should i put what. If possible can you give me a simple example code solution ?
Sure! afterChange would work as well! Make sure to check if the
operation
of the afterCheck is
create
in that case.
Definitely check out the docs first:
https://payloadcms.com/docs/hooks/collections#afterchangethe first code example is how you could do it! So:
import { CollectionConfig } from 'payload/types';
export const YourCollection: CollectionConfig = {
slug: 'yourslug',
fields: [
{ name: 'name', type: 'text'},
],
hooks: {
afterChange: [({doc, operation}) => {
if(operation === 'create') {
// create document here
}
}],
},
}
now let's say i have a collection called myCollection with two fields one is name, another is yourCollection which is relationTo this YourCollection. now i want to create myCollection afterCreating YourCollection.
inshort what i meant is i need that syntax. where we are creating that.
import { CollectionConfig } from 'payload/types';
export const YourCollection: CollectionConfig = {
slug: 'yourslug',
fields: [
{ name: 'name', type: 'text'},
],
hooks: {
afterChange: [({doc, operation}) => {
if(operation === 'create') {
await payload.create({
collection: 'myCollection',
data: {
yourCollection: doc.id,
name: 'some text'
},
});
}
}],
},
}
that should work! Just a simple payload.create call
"yourCollection" would be the relationTo field
Definitely also give
https://payloadcms.com/docs/local-api/overviewa read for the syntax for the payload local API (
payload.create
is part of it). Can do many other things as well, e.g. updating documents
Great thanks it
's
working fine
now if i want this field name: 'some text'
to be dynamic like it will contain the name of this collection and some other text something like that. how can i achieve that ?
You should be able to just use
name: doc.title+'some text'
or something like that, assuming you have a text field named
title
doc
contains all the data of your current document after it has been created, so you have access to it all via that variable!
Thanks a lot. You are awesome. Stay blessed.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.