Triggers - Trigger events - Trigger context variables

Triggers - Trigger events - Trigger context variables

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:
trigger triggerName on ObjectName (trigger_events) {
code_block
}
Example Trigger on Merchandise__c to send single mail before insert:
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 });

}
}
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:
  • Before triggers can be used to update or validate record values before they are saved to the database.
  • After triggers can be used to access field values that are set by the database (such as a record's Id or lastUpdated field), and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue.
Trigger context variables:

Variable
Usage
isExecuting
Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
isInsert
Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
isUpdate
Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
isDelete
Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
isBefore
Returns true if this trigger was fired before any record was saved.
isAfter
Returns true if this trigger was fired after all records were saved.
isUndelete
Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
new
Returns a list of the new versions of the sObject records.
Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers.
newMap
A map of IDs to the new versions of the sObject records.
Note that this map is only available in before update, after insert, and after update triggers.
old
Returns a list of the old versions of the sObject records.
Note that this sObject list is only available in update and delete triggers.
oldMap
A map of IDs to the old versions of the sObject records.
Note that this map is only available in update and delete triggers.
size
The total number of records in a trigger invocation, both old and new.


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. trigger countTasksOnLead on Task (after delete, after insert, after undelete, after update) {
  2. public set<ID> leadID = new set<ID>();                 // Set of Ids
  3. public list<Lead> leadToBeUpdated = new list<Lead>();   // List of Leads
  4. if(Trigger.isInsert || Trigger.isunDelete || Trigger.isUpdate)
  5. {
  6. for(task t: trigger.new){
  7. if(string.valueof(t.whoId).startsWith('00Q')) //Leads Id starts with '00Q'
  8. leadId.add(t.whoId);
  9. }
  10. }
  11. if(Trigger.isDelete)
  12. {
  13. for(task t: trigger.old){
  14. if(string.valueof(t.whoId).startsWith('00Q'))
  15. leadId.add(t.whoId);
  16. }
  17. }

  18. if(leadId.size()>0){
  19. for(lead l: [SELECT l.id, l.task_count__c, (select Id from Tasks where isClosed= false) from lead l where id in: leadId])
  20. {
  21. leadToBeUpdated.add(new lead(id = l.id, task_count__c=l.tasks.size()));

  22. }
  23. update leadToBeUpdated;
  24. }
  25. }












Creating Case Record When Field On Account Equals “CreateCase”


  1. trigger AccountTrigger on Account (after insert, after update) { 
  2. // Create an instance of your helper class
  3. AccountTriggerHelper helper = new AccountTriggerHelper(); 
  4. // 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 
  5. if((Trigger.isAfter && Trigger.isInsert) || (Trigger.isAfter && Trigger.isUpdate)){ 
  6. // Now call your helper method 
  7. helper.createCaseWhenNeeded(Trigger.new); 
  8.   } 
  9. }

  1. public class AccountTriggerHelper{
  2.    public void createCaseWhenNeeded(List<Account> accounts){
  3.        // We need to store a List of Cases to create.
  4.        List<Case> casesToCreate = new List<Case>();

  5.        // Loop over the accounts. Remember, we don't know how many accounts we will have
  6.        for(Account acc:accounts){
  7.            // This is where you need to determine what your condition will be.
  8.            // You will replicate this system with more if statements or else if
  9.            // statements
  10.            if(acc.Name == 'CreateCase'){
  11.                // Your account meets the criteria, create the case you want and
  12.                // add it to your List of cases
  13.                Case caseToAdd = new Case();

  14.                // Set up any fields you want
  15.                caseToAdd.Name = 'Test';
  16.                caseToAdd.Custom_Field__c = 'Something';
  17.                casesToCreate.add(caseToAdd);

  18.                // You could have also used the following...
  19.                // new Case(Name = 'Test',Custom_Field__c = 'Something');
  20.                // All you need to do is comma delimit all of the fields you want to add
  21.                // Depending on how many fields you want to add, it can be cleaner to 
  22.                // create it like above and then just add it all in one statement
  23.            }
  24.        }

  25.        // You have your full List of cases to add, now just run the insert DML statement
  26.        insert cases;
  27.    }
}



Duplicate Check


  1. trigger DuplicateStudentCheck on Student__c (before insert) {

  2.        //Get all Student__c related to the incoming Student records in a single SOQL query.
  3.        Student__c[] studentsList = Trigger.new;
  4.        Set emailSet = new Set();
  5.        for(Student__c s : studentsList)
  6.        {
  7.         emailSet.add(s.Email__c);
  8.        }

  9.        //Get list of duplicate Students
  10.        List duplicateStudentList = [Select s.Name, s.Email__c From Student__c s
  11. where s.Email__c IN :emailSet];

  12.        Set duplicateEmailIds = new Set();

  13.        for(Student__c s : duplicateStudentList)
  14.        {
  15.         duplicateEmailIds.add(s.Email__c);
  16.        }

  17.        for(Student__c s : studentsList)
  18.        {
  19.            if(duplicateEmailIds.contains(s.Email__c))
  20.            {
  21.             s.Email__c.addError('Record already exist with same email Id');
  22.            }
  23.        }
  24. }
test 

  1. @isTest
  2. private class TestTriggers {

  3.     static testMethod void myUnitTest() {
  4.         Student__c s = new Student__c();
  5.         s.Name = 'Om Test';
  6.         s.l_Name__c = 'LastName';

  7.         Course__c c = new Course__c();
  8.         c.Name = 'SFDC';
  9.         c.Fees__c = 2000;
  10.         insert c;

  11.         s.Course__c = c.Id;
  12.         s.Installment_1__c = 2000;
  13.         s.Email__c = 'admin@shivasoft.in';
  14.         try
  15.         {
  16.          insert s;
  17.         }
  18.         catch(System.DMLException e)
  19.         {
  20.          System.assert(e.getMessage().contains('Record already exist with same email Id'));
  21.         }
  22.     }
  23. }




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

Popular Posts