×
Apex 编程教程Apex 环境Apex 示例Apex 数据类型Apex 变量Apex 字符串Apex 数组Apex 常量Apex 决策Apex 循环Apex 集合Apex 类Apex 类方法Apex 对象Apex 接口Apex DMLApex 数据库方法Apex SOSLApex SOQLApex 安全性Apex 调用Apex 触发器Apex 触发设计模式Governer Limits调节器限制Apex 批量处理Apex 调试Apex 测试Apex 部署Apex 字符串Apex 数组

Apex 触发器


Apex触发器类似于当特定事件发生时执行的存储过程。 它在记录事件发生之前和之后执行。

语法

trigger triggerName on ObjectName (trigger_events) { Trigger_code_block }

执行触发器

以下是我们可以触发触发器的事件:

  • insert
  • update
  • delete
  • merge
  • upsert
  • undelete


触发器示例1

假设我们收到业务要求,当客户的“客户状态”字段从非活动状态更改为活动状态时,我们需要创建发票记录。 为此,我们将通过以下步骤在APEX_Customer__c对象上创建触发器:


第1步:进入sObject


第2步:点击客户


第3步:点击触发器相关列表中的“新建”按钮,添加如下所示的触发代码。

//Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
	List InvoiceList = new List();
	for (APEX_Customer__c objCustomer: Trigger.new) {
		if (objCustomer.APEX_Customer_Status__c == 'Active') {
			APEX_Invoice__c objInvoice = new APEX_Invoice__c();
			objInvoice.APEX_Status__c = 'Pending';
			InvoiceList.add(objInvoice);
		}
	}
	//DML to insert the Invoice List in SFDC
	insert InvoiceList;
}

说明:

Trigger.new:这这是上下文变量,用于存储当前正在插入或更新的触发器上下文中的记录。 在这种情况下,此变量具有已更新的Customer对象的记录。


还有上下文中可用的其他上下文变量:trigger.old,trigger.newMap,trigger.OldMap。

触发器示例2

当对客户记录进行更新操作时,将执行上述触发器。 但是,假设我们希望仅在客户状态从非活动更改为活动而不是每次都更改时插入发票记录。

为此,我们可以使用另一个上下文变量trigger.oldMap,它将密钥作为记录id和值存储为旧记录值。

//Modified Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
	List InvoiceList = new List();
	for (APEX_Customer__c objCustomer: Trigger.new) {
		//condition to check the old value and new value
		if (objCustomer.APEX_Customer_Status__c == 'Active' && trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
			APEX_Invoice__c objInvoice = new APEX_Invoice__c();
			objInvoice.APEX_Status__c = 'Pending';
			InvoiceList.add(objInvoice);
		}
	}

	//DML to insert the Invoice List in SFDC
	insert InvoiceList;
}

示例:

我们使用Trigger.oldMap变量,如前所述,它是一个上下文变量,用于存储正在更新的记录的Id和旧值。


分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)