Friday, 4 January 2013

Roll-up summary Using Trigger:-


Here 
ChildExample2__c  is child object and Amount__c is custom field in this object.
Example2__c  is parent object and Total_Amount__c is custom field in this object.

Roll-up summary means add all Amount fields in Child records , then update total amount with
the parent record.

Here we go

 
    trigger Testduplicate7 on ChildExample2__c (after delete, after insert, after update) {
    set<Id> Ids = new set<Id>();
    if(trigger.isInsert || trigger.isUpdate){
        for(ChildExample2__c p : trigger.new){
            Ids.add(p.Example2__c);
        }
    }
    if(trigger.isDelete){
        for(ChildExample2__c p : trigger.old){
            Ids.add(p.Example2__c);
        }
    }
    map<Id,Double> smap = new map <Id,Double>();
    for(AggregateResult q : [select Example2__c,sum(Amount__c)from ChildExample2__c where Example2__c IN :Ids group by Example2__c]){
        smap.put((Id)q.get('Example2__c'),(Double)q.get('expr0'));
    }
    List<Example2__c> ls = new List<Example2__c>();
    for(Example2__c a : [Select Id, Total_Amount__c from Example2__c where Id IN :Ids]){
        Double PipelineSum = smap.get(a.Id);
        a.Total_Amount__c = PipelineSum;
        ls.add(a);
    }
    update ls;
}


(OR) Another method here we go

/*Rollup summary on any field*/
trigger Test7 on ChildExample2__c (after insert,after update,after delete){
    if(Trigger.isinsert){
        Map<id,decimal> total = new Map<id,decimal>();
        for(ChildExample2__c ch :trigger.new){
            if(ch.amount__c!=null){
                if(total.get(ch.Example2__c)==null){
                    total.put(ch.Example2__c,ch.amount__c);
                }
                else
                {
                    decimal amt = 0;
                    amt = total.get(ch.Example2__c)+ch.amount__c;
                    total.put(ch.Example2__c,amt);
               
                }
            }
        }
        list<Example2__c> elist= new list<Example2__c>();
        list<Example2__c> exList = [select total_amount__c from Example2__c where id in:total.keyset()];
        for(Example2__c a:exList){
            if(a.total_amount__c==null){
                a.total_amount__c=0;
            }
            a.total_amount__c+=total.get(a.id);
            elist.add(a);
        }
        update elist;
    }
    if(Trigger.isUpdate){
        Map<id,decimal> total = new Map<id,decimal>();
        List<ChildExample2__c> chOld = Trigger.old;
        for(ChildExample2__c ch :trigger.New){
            if(ch.amount__c!=null){
                total.put(ch.Example2__c,ch.amount__c);
            }
            else{
                total.put(ch.Example2__c,0);
            }
        }
        Map<id,decimal> acc = new Map<id,decimal>();
        for(ChildExample2__c chod :trigger.old){
            if(chod.amount__c!=null){
                acc.put(chod.Example2__c,chod.amount__c);
            }
            else{
                acc.put(chod.Example2__c,0);
            }
        }
        list<Example2__c> elist= new list<Example2__c>();
        list<Example2__c> exList = [select total_amount__c from Example2__c where id in:total.keyset()];
        for(Example2__c a:exList){
            if(a.total_amount__c==null){
                a.total_amount__c=0;
            }
            System.Debug('==============sizw='+acc.get(a.id));
            a.total_amount__c+=total.get(a.id)-acc.get(a.id);
            elist.add(a);
        }
        update elist;
    }
    if(Trigger.isDelete){
        List<ChildExample2__c> chOld = Trigger.old;
        Map<id,decimal> acc = new Map<id,decimal>();
        for(ChildExample2__c chod :trigger.old){
            if(chod.amount__c!=null){
                acc.put(chod.Example2__c,chod.amount__c);
            }
        }
        list<Example2__c> elist= new list<Example2__c>();
        list<Example2__c> exList = [select total_amount__c from Example2__c where id in:acc.keyset()];
        for(Example2__c a:exList){
            if(a.total_amount__c==null){
                a.total_amount__c=0;
            }
            a.total_amount__c-=acc.get(a.id);
            elist.add(a);
        }
        update elist;
    }
}



Thursday, 3 January 2013

Working With Triggers:-


How to create a Trigger:-

Setup--> App setup--> Any object -->Triggers

Use of Trigger:- Triggers will do automate the Process.

When the Trigger will fire:- When we did DML operations in Records , on that time based on Event 
                                         Triggers will fire.

Here we have Some Events:-

Before Insert
Before Update
Before Delete
After Insert
After Update
After Delete

Example:-

Here we Have a scenario , In contact object we have a Email field, create one field 
domain__c in contact, When we create/update a record in Contact object ,
The Domain Name of Email field should update with domain__c field in same record.

trigger DomainName on Contact (before insert,before update)
{
   if(Trigger.isinsert){
       List<String> allEmailStrings=new List<String>();
       if(Trigger.isbefore){
           for(Contact allconnew:Trigger.new){
               if(allconnew.Email!=null){
                   //List<Contact> conEmailCompare=[select id,name,email from Contact where email=:allconnew.email];  
                   String strEmail = allconnew.email;
                   String strSubEmail = strEmail.substring(strEmail.indexOf('@'),strEmail.length());
                   System.debug('Final String:========> '+ strSubEmail);
                   String strActString = strSubEmail.substring(1,strSubEmail.indexOf('.'));
                   System.debug('Final String:========> '+ strActString);
                   allconnew.domain__c=strActString;
               }
            }
        }
   }
   if(Trigger.isupdate){
        List<String> allEmailStrings=new List<String>();
        if(Trigger.isbefore){
              for(Contact allconnew:Trigger.new){
                  if(allconnew.Email!=null){
                       String strEmail = allconnew.email;
                       String strSubEmail = strEmail.substring(strEmail.indexOf('@'),strEmail.length());
                       String strActString = strSubEmail.substring(1,strSubEmail.indexOf('.'));
                       System.debug('Final String:========> '+ strActString);
                       allconnew.domain__c=strActString;
                       System.debug('transfered=========>'+allconnew.domain__c);
                   }
               }
          }
    }
     
  }


Example2:-

 We take another scnario , In contact there is a lookup field called spouse on to contact.(self lookup).
When we click on look-up field in child record, the parent record spouse field should be child record name.

Here if a contact record name='Daniel'.
And spouse in the record of daniel is 'Mary'.
if i click mary lookup feild the daniel should be the spouse in the mary record.
it means the lookup value should change vice versa.


trigger MatchSpouse on Contact (after insert, before update) {
    List<Contact> spouses = new List<Contact>();
    Contact spouse;
    for (Contact c : Trigger.new){
        if (c.Spouse__c != null){
            spouse = [select id,Spouse__c from Contact where Id=: c.Spouse__c ];
            if(spouse.Spouse__c != c.id){
                spouse.Spouse__c = c.id;
                spouses.add(spouse);
            }
        }
    }
    if(spouses.size()>0 && staticFlag.a ){
        staticFlag.a = false;
        update spouses;
    }
}