Sunday 5 October 2014

Trigger.newmap and Trigger.oldmap in salesforce



                                             Trigger.newMap && Trigger.oldMap
  • Trigger.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.

  • Trigger.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.


Trigger updatecontact on Account (before update,after delete) {
 
  if(trigger.isbefore && trigger.isupdate){
  map<id,account> mapcon = trigger.newmap;
  list<contact> cont = new list<contact>();
  list<contact> con = [select id,phone,accountid from contact where accountid in : mapcon.keyset()];
  for(contact c : con){
   c.phone = mapcon.get(c.accountid).phone;
   cont.add(c);

  }
  update cont;
}
  if(trigger.isafter && trigger.isdelete){
   map<id,account> delcon = trigger.oldmap;
   list<contact> ccc = [select id from contact where accountid in : delcon.keyset()];
   delete ccc;
 
 
  }
}
-----------------------------------------Test class--------------------------------------------------------
@isTest
public class testupdatecon {
    public static testmethod void main(){
        account a = new account(name = 'gopi',phone = '0000000000');
        insert a;
        contact c = new contact(lastname = 'love',phone = a.phone,accountid = a.id);
        insert c;
           
           
        account aa = [select id,name,phone,(select id,phone from contacts) from account where id =: c.AccountId];
        update aa;
        delete aa;
       
    }  
    }

                                   



No comments:

Post a Comment

Complete Salesforce CPQ training Free videos

Salesforcestart:: We are excited to announce that our YouTube channel, Salesforcestart, is your one-stop-shop for all things Salesforce CPQ!...