Triggers - Trigger events - Trigger context variables
Triggers
A trigger
is a piece of code that executes before or after records of a particular type
are inserted, updated, or deleted from the Force.com platform database.
Every trigger runs with a set of
context variables that provide access to the records that caused the trigger
to fire.
All triggers run in bulk; that is, they
process several records at once.
Triggers
have the following syntax:
Example Trigger on Merchandise__c to
send single mail before insert:
The events you can specify are:
1.
before
insert
2.
before
update
3.
before
delete
4.
after
insert
5.
after
update
6.
after
delete
7.
after
undelete
Triggers can be divided into two types:
Trigger
context variables:
|
Triggers Samples
trigger AccountTrigger on Account (before Insert) {
HttpClass.clickme();
}
public with sharing class
HttpClass {
@Future
public static void clickme()
{
String
strurl='http://maps.googleapis.com/maps/api/geocode/xml?address=92618&sensor=false';
HttpRequest req=new HttpRequest();
req.setEndpoint(strurl);
req.setMethod('POST'); //
req.setMethod('GET');
string strbody='hi';
req.setBody(strbody);
req.setCompressed(true);
Http http=new Http();
HTTPResponse res=http.send(req);
string strRes=res.getbody();
system.debug('**** XML Data is
*****'+strRes);
// Parse either XML / JSON Response
using those methods (JSON / XML Parse Methods)
}
}
-----------
trigger affectedTrigger on Account (before delete,
after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(HelperClass.firstRun){
Trigger.old[0].addError('Before
Account Delete Error');
HelperClass.firstRun=false;
}
}
}
}
public class HelperClass {
public static boolean firstRun = true;
}
-------
trigger CandidateTrigger on Candidate__c (after
Insert) {
list<String> setEmails = new
list<String>();
for(Candidate__c objC : trigger.new){
setEmails.add(objC.email__c);
}
for(Candidate__c objC : trigger.new){
string smail = '<html><table
border=\"1\"><tr><td>Candidate
Name</td><td>'+objC.Name+'</td></tr></table></html>';
Messaging.SingleEmailMessage
mail = new Messaging.SingleEmailMessage();
String[] toAddresses =
setEmails;
mail.setBccAddresses(toAddresses);
mail.setSenderDisplayName('Salesforce');
mail.setSubject('Real
Property Utilization and Disposal - Resource Center');
mail.setBccSender(true);
mail.setPlainTextBody(smail);
mail.setHtmlBody(smail);
Messaging.sendEmail(new
Messaging.SingleEmailMessage[] { mail });
}
}
---------
trigger ContactTrigger on Contact (after insert) {
for(Contact objC : trigger.new){
Messaging.SingleEmailMessage mail
= new
Messaging.SingleEmailMessage();
mail.setTargetObjectId(objC.Id);
// The email template ID used for the email
mail.setTemplateId('00X90000001Ak3W');
mail.setBccSender(false);
mail.setUseSignature(false);
mail.setReplyTo('recruiting@acme.com');
mail.setSenderDisplayName('HR Recruiting');
mail.setSaveAsActivity(false);
Messaging.sendEmail(new
Messaging.SingleEmailMessage[] { mail });
}
}
----------
trigger EmployeeTrigger on Employee__c (after
insert) {
AccInsertCls objAIC = new AccInsertCls();
objAIC.m1(trigger.new);
}
public class AccInsertCls{
public List<Account> lstA = new
List<Account>();
public void m1(List<Employee__c>
lstE){
for(Employee__c objE : lstE){
Account objA = new Account();
objA.Name =
objE.Employee_Name__c;
lstA.add(objA);
}
insert lstA;
}
}
-------
trigger HelloWorldTrigger on Book__c (before
insert) {
Book__c[] books = Trigger.new;
MyHelloWorld.applyDiscount(books);
}
public class MyHelloWorld {
public static void
applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}
}
---------
trigger newProInfoTrigger on Merchandise__c (before
insert) {
for(Merchandise__c mObj :
trigger.new) {
Messaging.SingleEmailMessage
mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new
String[] {mObj.Supplier_E_Mail__c};
String[] ccAddresses = new
String[] {'sfdc.gsk@gmail.com'};
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
mail.setReplyTo('emailsravan@gmail.com');
mail.setSenderDisplayName('Merchandise
- Inventory Management Section');
mail.setSubject('Product' +
mObj.Name + 'has been received');
mail.setBccSender(false);
// Optionally append the
salesforce.com email signature to the email.
// The email address of the
user executing the Apex Code will be used.
mail.setUseSignature(false);
// Specify the text content of
the email.
mail.setPlainTextBody('New
Product in Warehouse: ' + case.Id + ' has been purchased.');
mail.setHtmlBody('New
Product:<b> ' + case.Id +' </b>is procured.<p>'+
'To view your product <a
href=https://ap1.salesforce.com/'+case.Id+'>click here.</a>');
// Send the email you have
created.
Messaging.sendEmail(new
Messaging.SingleEmailMessage[] { mail });
}
}
-----------
trigger RestrictInvoiceDeletion on
Invoice_Statement__c (before delete) {
// With each of the invoice
statements targeted by the trigger
// and that have line items,
add an error to prevent them
// from being deleted.
for (Invoice_Statement__c
invoice :
[SELECT Id
FROM Invoice_Statement__c
WHERE Id IN (SELECT Invoice_Statement__c FROM
Line_Item__c) AND
Id IN :Trigger.old]){
Trigger.oldMap.get(invoice.Id).addError('Cannot
delete invoice statement with line items');
}
}
----------------
Trigger to count the no. of open tasks on a Lead
1. first create a field task_count__c in Lead
2. now create a trigger on task Setup>>Customize>>Activities>>TaskTriggers
1. first create a field task_count__c in Lead
2. now create a trigger on task Setup>>Customize>>Activities>>TaskTriggers
- trigger countTasksOnLead on Task (after delete, after insert, after undelete, after update) {
- public set<ID> leadID = new set<ID>(); // Set of Ids
- public list<Lead> leadToBeUpdated = new list<Lead>(); // List of Leads
- if(Trigger.isInsert || Trigger.isunDelete || Trigger.isUpdate)
- {
- for(task t: trigger.new){
- if(string.valueof(t.whoId).startsWith('00Q')) //Leads Id starts with '00Q'
- leadId.add(t.whoId);
- }
- }
- if(Trigger.isDelete)
- {
- for(task t: trigger.old){
- if(string.valueof(t.whoId).startsWith('00Q'))
- leadId.add(t.whoId);
- }
- }
- if(leadId.size()>0){
- for(lead l: [SELECT l.id, l.task_count__c, (select Id from Tasks where isClosed= false) from lead l where id in: leadId])
- {
- leadToBeUpdated.add(new lead(id = l.id, task_count__c=l.tasks.size()));
- }
- update leadToBeUpdated;
- }
- }
Creating Case Record When Field On Account Equals “CreateCase”
- trigger AccountTrigger on Account (after insert, after update) {
- // Create an instance of your helper class
- AccountTriggerHelper helper = new AccountTriggerHelper();
- // Even though this trigger only works after insert or after update currently, there is nothing to stop you from adding to it in the future. Adding this logic will allow you to expand in the future. This says run if the trigger is after the insert OR after the update
- if((Trigger.isAfter && Trigger.isInsert) || (Trigger.isAfter && Trigger.isUpdate)){
- // Now call your helper method
- helper.createCaseWhenNeeded(Trigger.new);
- }
- }
- public class AccountTriggerHelper{
- public void createCaseWhenNeeded(List<Account> accounts){
- // We need to store a List of Cases to create.
- List<Case> casesToCreate = new List<Case>();
- // Loop over the accounts. Remember, we don't know how many accounts we will have
- for(Account acc:accounts){
- // This is where you need to determine what your condition will be.
- // You will replicate this system with more if statements or else if
- // statements
- if(acc.Name == 'CreateCase'){
- // Your account meets the criteria, create the case you want and
- // add it to your List of cases
- Case caseToAdd = new Case();
- // Set up any fields you want
- caseToAdd.Name = 'Test';
- caseToAdd.Custom_Field__c = 'Something';
- casesToCreate.add(caseToAdd);
- // You could have also used the following...
- // new Case(Name = 'Test',Custom_Field__c = 'Something');
- // All you need to do is comma delimit all of the fields you want to add
- // Depending on how many fields you want to add, it can be cleaner to
- // create it like above and then just add it all in one statement
- }
- }
- // You have your full List of cases to add, now just run the insert DML statement
- insert cases;
- }
}
Duplicate Check
- trigger DuplicateStudentCheck on Student__c (before insert) {
- //Get all Student__c related to the incoming Student records in a single SOQL query.
- Student__c[] studentsList = Trigger.new;
- Set emailSet = new Set();
- for(Student__c s : studentsList)
- {
- emailSet.add(s.Email__c);
- }
- //Get list of duplicate Students
- List duplicateStudentList = [Select s.Name, s.Email__c From Student__c s
- where s.Email__c IN :emailSet];
- Set duplicateEmailIds = new Set();
- for(Student__c s : duplicateStudentList)
- {
- duplicateEmailIds.add(s.Email__c);
- }
- for(Student__c s : studentsList)
- {
- if(duplicateEmailIds.contains(s.Email__c))
- {
- s.Email__c.addError('Record already exist with same email Id');
- }
- }
- }
test
- @isTest
- private class TestTriggers {
- static testMethod void myUnitTest() {
- Student__c s = new Student__c();
- s.Name = 'Om Test';
- s.l_Name__c = 'LastName';
- Course__c c = new Course__c();
- c.Name = 'SFDC';
- c.Fees__c = 2000;
- insert c;
- s.Course__c = c.Id;
- s.Installment_1__c = 2000;
- s.Email__c = 'admin@shivasoft.in';
- try
- {
- insert s;
- }
- catch(System.DMLException e)
- {
- System.assert(e.getMessage().contains('Record already exist with same email Id'));
- }
- }
- }
Prevent duplicate Lead emil
trigger biuLead on Lead (before insert, before update)
{
// Get a list of all emails being inserted or updated.
set<String> emailSet = new set<String>();
for (Lead l : system.trigger.new)
{
if ((l.Email != null) &&
(system.trigger.isInsert ||
(l.Email != system.trigger.oldMap.get(l.Id).Email)))
{
// Make sure a DIFFERENT new Lead isn't also a duplicate.
if (emailSet.contains(l.Email))
{
l.Email.addError('Sorry, but more than one new Lead ' +
'has the same email address.');
}
else
{
emailSet.add(l.Email);
}
}
}
// Get all EXISTING open Leads that have the same email address.
list<Lead> leadList =
[SELECT Email FROM Lead WHERE Email IN :emailSet];
if (leadList.size() > 0)
{
system.trigger.new[0].addError('Sorry, but there is already an ' +
'open Lead with that Email address.');
}
}
Comments
Post a Comment