Ask Search:
Chirag VermaChirag Verma 

how to get particular record id in For each loop

I have given a interview and interviewer ask me to write a trigger with this condition:

to do the work same as roll-up summary in contacts to capture the age from all the contacts related to a particular account. so i write this trigger.....but he said that at (line 4) for all the different contacts related to different account, your code will add the age of all the contacts related to that account or not to the a single account record not to the designated account related records.

So i have to ask that, how should we differentiate at (line 5) to add the contacts age for that particular Account only.


Trigger abc on Contact (before insert, before update){
    If(Tigger.isInsert){
        List<Account> a1 = [Select name,Tage from Account where id =:Trigger.new.AccountName];
        For(Account aa1: a1){
            aa1.Tage =+ Trigger.new[0].age;
                    
        }update aa1 or update a1;
    }
    If(Tigger.isUpdate){
        List<Account> a2 = [Select name,Tage from Account where id =:Trigger.new.AccountName];
        For(Account aa2: a2){
            If(Trigger.new.age !=Trigger.old.age){
            aa2.Tage =- Trigger.old[0].age;    
            aa2.Tage =+ Trigger.new[0].age;
                 }   
        }update aa2 or update a2; 
    }
}



Kindly reply as early as possible as i have to go back there tomorrow for same Interview.

Regards
Chirag Verma
roxyverma111@gmail.com
Best Answer chosen by Moderator (salesforce.com) 
Maria BelliMaria Belli
You may want to try posting your question at one of the following sites that are geared more toward developers:

http://boards.developerforce.com/sforce/?category.id=developers

or

http://salesforce.stackexchange.com