Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Trigger trigger of Salesforce

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you the relevant knowledge about how to use Salesforce's Trigger trigger. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's learn about it.

One. Apex Trigger trigger

Apex triggers (Apex Triggers) are a special Apex class. Apex triggers are similar to stored procedures that execute when a particular event occurs. It is executed before and after recording the event. Its main function is to automatically perform a series of operations before or after a record is inserted, modified, or deleted. Each Trigger class must correspond to an object.

The syntax of Trigger is the same as that of ordinary Apex classes.

Before creating a Trigger, Salesforce recommends that developers consider whether the same operation can be done through the functions in the Salesforce settings interface, such as validation rules (Validation Rule), workflow rules (Workflow Rule), and so on. If possible, use them first.

Two. The structure and trigger events of Apex Trigger

Grammatical structure:

/ / Syntax structure trigger triggerName on ObjectName (trigger_events) {Trigger_code_block} / / description trigger Trigger name (trigger name) on object name (trigger event) {/ / Do something}

The Trigger class must start with the keyword "trigger", followed by the name of the Trigger. Next comes the "on" keyword, followed by the name of the object corresponding to Trigger. The event that triggers the Trigger is written in parentheses after the object name.

There are several types of events triggered by Trigger:

Insert / / add

Update / / modify

Delete / / Delete

Merge / / merge

Upsert / / add or modify, that is, if the data is added without the data, it will be modified.

Upsert principle: upsert determines whether this record exists by the existence of this ID, 1. If this ID does not exist, then the insert operation is performed; 2. If there is and there is only one ID, the update operation is performed; 3. If there is and there is more than one ID, DMLException is thrown

Undelete / / cancel deletion, you can undelete deleted records that exist in the Recycle Bin

The types of Trigger triggers are as follows:

Before trigger is usually used to update or validate data before they are saved in the database

After trigger is usually used to save fields that access the system (Id, etc.).

Meow understands them as pre-triggers and post-triggers, that is, what to do before and after triggering an event. (this is only Xiao Meow's personal understanding, just to make it easier to understand / learn)

Three. Design thought

The design idea of Trigger is' One Trigger per Object', that is, 'one object, one trigger'. We can combine all possible triggers of a particular object into a single trigger.

Note: the static keyword cannot be included in the trigger code block.

The benefits of this design pattern are:

❃ reusability: put logic in a class that can now be reused outside of triggers, such as Visualforce pages, test classes, batch Apex, and so on. There is no need to copy the code!

❃ simplicity: in the main trigger, each "trigger" is reduced to only two lines of code. An object-oriented code base is more organized, predictable, and modular!

❃ controls the execution order: in Apex, "there is no guarantee of the execution order of multiple triggers on the same object." This mode gives you full control over orders.

❃ code style: whether or not you take advantage of any of the above advantages, you will look like an Apex master server using this mode.

Four. Common variable

Many contextual variables are encapsulated in the Trigger class, which are often used in development.

IsExecuting: the context of the current Apex code is the trigger environment, and true is returned if it is not VF, otherwise false is returned.

IsInsert: whether the current operation is adding operation, return true, otherwise return false

IsUpdate: whether the current operation is performing a modification operation, return true, otherwise return false

IsDelete: whether the current operation is in the process of deleting, return true, otherwise return false

IsBefore: whether the current operation is performed before save. It returns true, otherwise returns false.

IsAfter: whether the current operation is operated after save, true is returned, otherwise false is returned.

IsUndelete: whether the current operation is after replying data in the Recycle Bin. Return true, otherwise return false.

Note: variables of the above Boolean type are used to mark the status of Trigger or data.

New: returns a list of the latest data from sObject's records

NewMap: returns a Map collection that maps ID to the latest data list

Old: returns a list of previous data modified by sObject's records

OldMap: returns a Map collection that maps ID to a modified previous data list

Size: the total number of data called in the trigger, including new and old.

Among them, new, new Map, old and oldMap are subject to usage restrictions, which need to be highlighted:

New can only be used to return a list when performing trigger operations of insert and update and the type is before.

You can use newMap to return the map collection only when newMap is applicable to before update,after insert and trigger operations of after update.

Old and oldMap are only available for update and delete operations to use old and oldMap.

Simply put, Trigger.New and Trigger.Old are two predefined variables that can be used in each Trigger class. The former represents the data to be inserted and updated, while the latter represents the data before update and deletion. They may contain a piece of data or a set of data, depending on the state when the Trigger is triggered.

Note: Trigger.New does not exist in the delete operation because there is no data after deletion, while there is no insert operation in Trigger.Old because there is no data before the data is inserted.

Five. The use of Trigger triggers

At present, there are two main ways for Meow to use trigger: the first is to directly use trigger to write business logic in the internal block of trigger, and the second is to encapsulate trigger through Handler.

1) write the code directly in the internal block of Trigger:

Trigger AccountBeforeDelete on Account (before delete) {if (Trigger.isBefore) {/ / append data if (Trigger.isDelete) {List dlist = new List () to SFDelete c For (Account a: Trigger.old) {dlist.add (new SFDelete__c (delSfId__c = a.Id, tableName__c = 'Account', dataOwnerId__c = a.OwnerId));} ControllerUtil.insSFDelete (dlist);}

2) encapsulate trigger through Handler:

Through Handler, each Object can create its own Handler, write trigger business logic in its own Handler, and instantiate through Factory to achieve better scalability and readability.

2.1) create a TriggerHandler parent class

In public abstract class TriggerHandler {/ * Trigger, new,newMap,old,oldMap variables are encapsulated at runtime, where new and old return types are List newMap and oldMap return types are Map * / protected Map oldMap {get;set;} protected Map newMap {get;set;} protected List listNew {get;set;} protected List listOld {get;set } / * the following points should be noted when encapsulating trigger: 1.trigger.new can only be used for insert and update, and trigger must be before; 2.trigger.old for update and delete; 3.trigger.newMap can only be used for before update,after insert and after update; 4.trigger.oldMap can only be used for update and delete. * / public interface MyTrigger {void beforeInsert (SObject currentObject); void beforeUpdate (SObject oldSobject, SObject currentObject); void beforeDelete (SObject currentObject); void afterInsert (SObject currentObject); void afterUpdate (SObject oldSobject, SObject currentObject); void afterDelete (SObject currentObject); Boolean skipExecution ();}}

2.2) create the Handler of related objects, inherit TriggerHandler and implement its MyTrigger interface, and implement related methods.

Public class GoodsHandler extends TriggerHandler implements TriggerHandler.MyTrigger {public GoodsHandler () {/ / TODO Construcion} public void beforeInsert (SObject currentObject) {/ / TODO beforeInsert} public void afterInsert (SObject currentObject) {/ / TODO afterInsert} public void beforeUpdate (SObject oldSobject, SObject currentObject) {/ / TODO beforeUpdate} public void beforeDelete (SObject currentObject) {/ / TODO beforeDelete} public void afterUpdate (SObject oldSobject SObject currentObject) {} public void afterDelete (SObject currentObject) {} public Boolean skipExecution () {return false }}

Create a TriggerFactory, which is used to instantiate the Handler of Trigger and perform the corresponding before or after operation, where MyException is a custom exception class.

Public class MyException extends Exception {} public class TriggerFactory {/ * instantiate Handler and automatically execute Trigger * / public static void instanceHandler (Schema.SObjectType objectToken) {TriggerHandler.MyTrigger myTriggerHandler = getTriggerByObjectToken (objectToken); if (myTriggerHandler = = null) {throw new MyException ('trigger' without this object token) if executeTrigger is not skipped } if (! myTriggerHandler.skipExecution ()) {executeTrigger (myTriggerHandler);}} / * when executing trigger, you should pay attention to the following: 1.trigger.new can only be used for insert and update, and trigger must be before; 2.trigger.old for update and delete; 3.trigger.newMap can only be used for before update,after insert and after update. 4.trigger.oldMap can only be used in update and delete. * / public static void executeTrigger (TriggerHandler.MyTrigger myTriggerHandler) {/ / trigger is divided into isBefore and isAfter if (Trigger.isBefore) {if (Trigger.isInsert) {for (SObject currentObject: Trigger.new) {myTriggerHandler.beforeInsert (currentObject) }} else if (Trigger.isUpdate) {for (SObject oldObject: Trigger.old) {myTriggerHandler.beforeUpdate (oldObject, Trigger.newMap.get (oldObject.Id)) }} else if (Trigger.isDelete) {for (SObject currentObject: Trigger.old) {myTriggerHandler.beforeDelete (currentObject) } else {/ / isAfter if (Trigger.isInsert) {for (SObject currentObject: Trigger.new) {myTriggerHandler.afterInsert (currentObject) }} else if (Trigger.isUpdate) {for (SObject oldObject: Trigger.old) {myTriggerHandler.afterUpdate (oldObject, Trigger.newMap.get (oldObject.Id)) }} else if (Trigger.isDelete) {for (SObject currentObject: Trigger.old) {myTriggerHandler.afterDelete (currentObject) }} / * this method is used to return the trigger of a specific object. If you add a trigger of an object, add the corresponding matching processing in this method. At the same time, the Handler of this object must inherit TriggerHandler and implement a different Object Token for each Object of the TriggerHandler.MyTrigger. So it is more convenient to use Token as a parameter * / public static TriggerHandler.MyTrigger getTriggerByObjectToken (Schema.SObjectType objectToken) {if (objectToken = = Goods__c.sObjectType) {return new GoodsHandler () } / / TODO there are other Object needs to use trigger can inherit the TriggerHandler implementation of which MyTrigger and then configure return null;}} here

2.4) the instantiation method of calling Factory from the trigger of the corresponding Object

Trigger GoodsTrigger on Goods__c (before delete, before update) {TriggerFactory.instanceHandler (Goods__c.sObjectType);}

When the Goods__c field performs delete or update operations, save automatically triggers GoodsTrigger,GoodsTrigger to execute the instanceHandler method of TriggerFactory, which calls the instanceHandler and executeTrigger functions to execute the Goods__c table trigger business logic to be handled by the GoodsHandler class.

Tip: if the business is relatively simple, the first way can be used, and the development efficiency is high; if the business is relatively complex, the second way can write business logic more clearly in the corresponding Handler module, which is convenient for later maintenance and better readability.

These are all the contents of the article "how to use Salesforce's Trigger triggers". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report