Monday, February 26, 2018

Apex triggers


Number of Child Record Count on Parent Record Using Trigger:
------------------------------------------------------------

Trigger ContactCountTrigger on Contact(After insert,After Delete,After Undelete)
{
  Set<Id> setAccountIds = new Set<Id>();
 
  //Whenever your working with After Undelete operation you can access data through
  //Trigger.new or Trigger.newMap but not with Trigger.old or Trigger.oldmap variables
  if(Trigger.isInsert || Trigger.isUndelete)
  {
   for(Contact con : Trigger.new)
   {
    setAccountIds.add(con.AccountId);
   }
  }
 
  if(Trigger.isDelete)
  {
   //if you use Trigger.new below in place of Trigger.old you will end up with
   //System.NullPointerException:Attempt to de-reference a null object
   for(Contact con : Trigger.old)
   {
    setAccountIds.add(con.AccountId);
   }
  }
 
 List<Account> listAccs = [Select id,name,number_of_contacts__c ,(Select id from contacts) from Account where Id in : setAccountIds];
  for(Account acc :listAccs)
  {
   acc.number_of_contacts__c = acc.contacts.size();
  }
  update listAccs;
 
 ======================================================  End ======================================
 Copying Account Address to Contact Address:
 -------------------------------------------

 trigger UpdateAddress on Account (after update) {
    Set<Id> accountIds = new Set<Id>();
    for (Account a : Trigger.new) {
        Account old = Trigger.oldMap.get(a.Id);
        if (a.BillingStreet != old.BillingStreet || ...) {
            accountIds.add(a.Id);
        }
    }
    if (accountIds.size() > 0) {
        Contact[] updates = [
                select Id, AccountId
                from Contact
                where AccountId in :accountIds
                ];
        for (Contact c : updates) {
            Account a = Trigger.newMap.get(c.AccountId);
            c.BillingStreet = a.BillingStreet;
            ...
        }
        update updates;
    }
}
======================================================= End ==============================================
https://tekslate.com/15-sample-triggers-different-scenarios/
======================================================= End ==============================================
Difference Between Insert And Database.Insert
---------------------------------------------
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));

// DML statement
insert acctList;

Database.inser:
---------------
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));

// DML statement
Database.SaveResult[] srList = Database.insert(acctList, false);
//If you specify false for this parameter and if a record fails, the remainder of DML operations can still succeed.
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors               
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                   
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}
======================================================== End =====================================
trigger updatechaildrecords on Account (After update) { Set<Id> accountIds = new Set<Id>(); List<Contact> childrenToUpdate = new List<Contact>(); for (Account a : Trigger.new) { accountIds.add(a.Id); } list<contact> conlist = [select id,accountId,Title from contact where accountId in:accountIds]; for (Contact c : conlist ) { Account a = Trigger.newMap.get(c.AccountId); c.Title = a.Industry; childrenToUpdate.add(c); } update childrenToUpdate; }
   
   
======================================================== End ==============================================

trigger ContactsCreation on Account (after insert) {
 list<contact> listContact = new list<contact>();
 map<id,decimal> mapAcc=new map<id,decimal>();
 for(Account acc:trigger.new){
 mapAcc.put(acc.id,acc.Number_of_Locations__c);
 }
 if(mapAcc.size()>0 && mapAcc!=null){
 for(Id accId:mapAcc.keyset()){
 for(integer i=0;i<mapAcc.get(accId);i++){
 contact newContact=new contact();
 newContact.accountid=accId;
 newContact.lastname='contact'+i;
 listContact.add(newContact);
 }
 }
 }
 if(listContact.size()>0 && listContact!=null)
 insert listContact;
 }
 ======================================== End =====================================
 Static methods, variables, or initialization code are associated with a class, and are only allowed in outer classes.

When you declare a method or variable as static, it's initialized only once when a class is loaded. All static member variables in a class are initialized before any object of the class is created.  Indeed they aren't transmitted as part of the view state for a Visualforce page.
Using static variables will cause only one instance of the variable to be loaded when the application loads and that variable will not go out of memory until the app is closed.  It holds information that is common to all instances on a class and It is shared between them instead of being created a new with each instance.


while


Transient keyword to declare instance variable that can not be saved and should not transmitted as part of view state for visual force page.
Basically ,View State is an encrypted, hidden <input> field on a Visualforce page that keeps track of Apex controller state & Visualforce page state between server requests. This field is only generated when there is an <apex:form> tag present on a page.


ViewState is only used on a single page that handles postbacks. Once you redirect to the new page, the ViewState is lost.

============================================ End =========================================

rigger AccountDeletion on Account (before delete) {
  
    // Prevent the deletion of accounts if they have related contacts.
    for (Account a : [SELECT Id FROM Account
                     WHERE Id IN (SELECT AccountId FROM Opportunity) AND
                     Id IN :Trigger.old]) {
        Trigger.oldMap.get(a.Id).addError(
            'Cannot delete account with related opportunities.');
    }
=================================================  End =====================================
trigger updateContactsOnAddressChange on Account(before update) {
   
    Map<Id, Account> acctsWithNewAddresses = new Map<Id, Account>();

  
    for (Integer i = 0; i < Trigger.new.size(); i++) {
   
        if (   (Trigger.old[i].ShippingCity != Trigger.new[i].ShippingCity)
            || (Trigger.old[i].ShippingCountry != Trigger.new[i].ShippingCountry)                                                
            || (Trigger.old[i].ShippingPostalCode != Trigger.new[i]. ShippingPostalCode)                                               
            || (Trigger.old[i].ShippingState != Trigger.new[i].ShippingState)                                                
            || (Trigger.old[i].ShippingStreet != Trigger.new[i].ShippingStreet) )
           {
            //acctsWithNewAddresses.put(Trigger.old[i].id,Trigger.new[i]);
                                               
        }
      
    }

    List<Contact> updatedContacts = new List<Contact>();
    for (Contact c : [SELECT id, accountId, MailingCity, MailingCountry, MailingPostalCode, MailingState, MailingStreet FROM contact
                      WHERE accountId in :acctsWithNewAddresses.keySet()]) {
        Account parentAccount = acctsWithNewAddresses.get(c.accountId);
        c.MailingCity = parentAccount.ShippingCity;
        c.MailingCountry = parentAccount.ShippingCountry;
        c.MailingPostalCode = parentAccount.ShippingPostalCode;
        c.MailingState = parentAccount.ShippingState;
        c.MailingStreet = parentAccount.ShippingStreet;
        updatedContacts.add(c);
    }
    update updatedContacts;
}
============================================== End ===================================================
trigger Call_AprovalProcess_In_Trigger on Account (before insert, before update) {
 for(Account acc:trigger.new){
    if(acc.AnnualRevenue < 2000){
       approval.ProcessSubmitRequest aprlPrcs = new Approval.ProcessSubmitRequest();    
       aprlPrcs .setComments('Submitting record for approval.');
       aprlPrcs.setObjectId(acc.id);
       approval.ProcessResult result = Approval.process(aprlPrcs);
    }
 }
}
============================================ End ======================================================
trigger Trigger_Account on Account (before insert, before update) {

    

      //Check for Request Type

    if(Trigger.isBefore) {

  

        //Check for Event Type

        if(Trigger.isInsert || Trigger.isUpdate) {

      

            //Loop through Account

            for(Account account : Trigger.New) {

                

             //Logic for showing custom label message on page in absence of Account Number

               if(account.AccountNumber == Null)

                   account.addError('label.Account_Label');

            }

        }

    }

}
============================================== End =================================================
trigger CannotDeleteAccountWithPhone on Account (before delete) {   
    for (Account Accts : trigger.old)
    {
        if (Accts.Phone != null)
        {
            Accts.addError('You cannot delete an Account bcz it conatins Phone Number');
           
        }
    }    
}
================================================== End =================================================
trigger AccountAddressTrigger on Account (before insert, before update)
{
   for(Account a : Trigger.new){
        If (a.Match_Billing_Address__c == true) {
            a.ShippingPostalCode = a.BillingPostalCode;
        }  
    }
}

================================================ End ===================================================
trigger BeforeDeleteConatct on Contact (Before Delete)
{
 Set<Id> conSet=Trigger.OldMap.keyset();
 List<Contact> listCon=[select id,phone from contact where id in:conset];

 for(Contact c:listCon)
 {
  if(c.Phone!=null)
  {
    System.debug('.......c......'+c);
       Contact actualRecord = Trigger.oldMap.get(c.Id);
    actualRecord.addError('you cant delete this contact bcz it conatins Phone Number');
   }
  }
}
=============================================== End ==================================================
Trigger CopyBillAddres on Contact(Before insert , before update)
{
 Set<Id> AccountIds =new Set<Id>();
 Map<id,account> mapAcc = new Map<id,account>();
 for(Contact con :Trigger.new)
 {
    AccountIds.add(con.AccountId);
 }

 for(account a : [select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry from account where id in : AccountIds])
 {
    mapAcc.put(a.id,a);
 }

 for(Contact con :Trigger.new)
 {
    con.MailingStreet = mapAcc.get(con.AccountId).BillingStreet;
    con.MailingCity = mapAcc.get(con.AccountId).BillingCity;
    con.MailingState = mapAcc.get(con.AccountId).BillingState;
    con.MailingPostalCode = mapAcc.get(con.AccountId).BillingPostalCode;
    con.mailingCountry = mapAcc.get(con.AccountId).BillingCountry;
}
}
================================================= End =======================================================
trigger Mpping on Contact (before insert) {
   Set<Id> accIdSet = new Set<Id>();
     for(Contact con: Trigger.new) {
        if(con.AccountId != null) {
            accIdSet.add(con.AccountId);
        }
    }
  List<Account> accList = [Select Id, Name, Type from Account where Id IN: accIdSet];
  for(Contact con: Trigger.new) { 
       for(Account acc: accList) {
                if(con.AccountId == acc.Id) {
                    con.Acc_Type__c = acc.Type;
                }               
            }
        }
}
================================================== End =========================================================
trigger Trigonstudent on contact(before insert){
    set<String> setExistingEmail = new set<String>();
     set<String> emailset=new set<String>();
        for(contact s:Trigger.new){       
              emailset.add(s.Email); 
              }
 List<contact> duplicatestudentlist=[select LastName,Email from Contact where Email in : emailset ];
   for(Contact con : duplicatestudentlist){
    setExistingEmail.add(con.email);
     }
     for(contact a:trigger.new){

      if(setExistingEmail.contains(a.email)){
         a.email.addError('Record already exist with some emailid');
      }
   }
 }
 ================================================== End =======================================================
 trigger ClosedOpportunityTrigger on Opportunity(after insert, after update) {
   
    List<Task> taskList = new List<Task>();

    for(Opportunity opp : Trigger.new) {
       
        if(Trigger.isInsert) {

            if(Opp.StageName == 'Closed Won') {

                taskList.add(new Task(Subject = 'Follow Up Test Task', WhatId = opp.Id));

            }

            //Only create Follow Up Task only once when Opp StageName changed to 'Closed Won' on Update

      
        }
         if(Trigger.isUpdate) {

            if(Opp.StageName == 'Closed Won' && Opp.StageName != Trigger.oldMap.get(opp.Id).StageName)
            {

                taskList.add(new Task(Subject = 'Follow Up Test Task', WhatId = opp.Id));

            }

        }
        if(taskList.size()>0) {      

        insert taskList;      

    }
   }
}
=============================================== End ==============================================

trigger CheckOpportunityOnLeadConvert on Lead (after update) {
      if (Trigger.new[0].ConvertedOpportunityId == null) {
          //Throw an error
           Trigger.new[0].addError('Please create an opportunity');
    
  }    
}
================================================ End ================================================
trigger HelloWorldTrigger on Book__c (before insert) {

   Book__c[] books = Trigger.new;

   MyHelloWorld.applyDiscount(books);
  
   Class:
  
   public class MyHelloWorld {
   public static void applyDiscount(Book__c[] books) {
      for (Book__c b :books){
         b.Price__c *= 0.9;
      }
   }
}
============================================= End ====================================================
Adding Related Records:
------------------------------

 trigger AddRelatedRecord on Account(after insert, after update) {
    List<Opportunity> oppList = new List<Opportunity>();
   
    // Get the related opportunities for the accounts in this trigger
    Map<Id,Account> acctsWithOpps = new Map<Id,Account>(
        [SELECT Id,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
   
    // Add an opportunity for each account if it doesn't already have one.
    // Iterate through each account.
    for(Account a : Trigger.New) {
        System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
        // Check if the account already has a related opportunity.
        if (acctsWithOpps.get(a.Id).Opportunities.size() == 0) {
            // If it doesn't, add a default opportunity
            oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       AccountId=a.Id));
        }          
    }

    if (oppList.size() > 0) {
        insert oppList;
    }
}
=============================  End =======================================

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.