0

I`m trying to create an Apex Trigger on an Object (Asset for example) to check if a specific Checkbox fields is true than execute a platform event (which I have a PE flow that updates the record)

I got this code, seems like I didn't call the event correctly-

trigger AssetTest on Asset (before insert) {
for(Asset asse : Trigger.New) {
    if(asse.Entitlements__c == true){
     EventBus.publish(TestAsset__e)
    }
 }
}

Thanks in advance.

5
  • What are you trying to publish TestAsset__e ? May 16, 2022 at 6:43
  • Nothing, just to execute it in order to trigger the related PE flow. May 16, 2022 at 6:49
  • It does not work like that you need to create the object and pass details to it and then publish. For eg: ErrorLog__e errorLog = new ErrorLog__e(); errorLog.Stacktrace__c = e.getStackTraceString(); EventBus.publish(errorLog); May 16, 2022 at 6:51
  • There isn't a possibility to make the PE listen to the change triggered by the apex trigger condition? any chance you can provide an example with the one I gave? thanks! May 16, 2022 at 6:54
  • If you implement a Flow instead of an Apex trigger when your object is changed, you can create a Platform Event without code. developer.salesforce.com/docs/atlas.en-us.platform_events.meta/…
    – identigral
    May 16, 2022 at 15:32

1 Answer 1

1

You need to create a platform event record, not just reference the platform event type. Change the publish call something like:

EventBus.publish(new TestAsset__e());

If your event doesn't contain any field values and you will simply do a query in the flow to discover the Asset records that need processing, you should ensure you only ever publish a single platform event in your transactions.

You can do this with a simple static Boolean variable (defaulted to false) in a helper class and use it in your logic called from your trigger something like:

if(asse.Entitlements__c && !Helper.alreadyPublished){
    EventBus.publish(new TestAsset__e());
    Helper.alreadyPublished = true;
}

Such boolean flags are often an anti-pattern in triggers, but work fine for this use case where the event content isn't important, just that one is raised to result in processing.

Make sure the event publish behaviour is after commit to avoid sending it too early when processing bulk asset creation.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .