function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Francois RouxFrancois Roux 

Trigger: update Account field from custom object (lookup)

I'm relatively new to Apex: I have a custom object with a lookup relationship to Accounts, and need to update an account field when a field from a custom object is populated with a value. I need a trigger. Any help?
Best Answer chosen by Francois Roux
Akhil AnilAkhil Anil
Hi Francois,

Below is the test class for that trigger with 100% code coverage.
 
@isTest
public class testUpdateAcct {
   
   static testmethod void invokeTrigger() {
      
      Account ac = new Account();
      
      ac.Name = 'Test Account';
      
      Database.SaveResult sr = Database.insert(ac, false);
      
      if(sr.isSuccess()) {

         Parent__c p = new Parent__c();
      
         p.Name = 'Test Parent';      
         
         p.Account__c = sr.getId();
         
         Database.SaveResult sr1 = Database.insert(p, false);
         
         if(sr1.isSuccess()) {
            
            Id pid = sr1.getId();
              
            Parent__c p1 = [Select Id, Name from Parent__c where Id =:pid];
            
            p1.child_count__c = 2;
            
            update p1;
            
            p1.child_count__c = 1;
            
            update p1;
                 
         }        
      
      }
       
   }

}



Thanks,
Akhil
 

All Answers

Shephali SwarnkarShephali Swarnkar
Hi Francois,
      can u provide ur requirement with more details like which field of account u want to update and what is ur custom object nd field name.

and also u can refer this link for more help
http://salesforce.stackexchange.com/questions/45232/need-help-writing-a-custom-object-trigger

Thanks
shephali
Akhil AnilAkhil Anil
Hi Francois,

You can refer the below example. In the Below example Parent__c object has a lookup relation to Account object and the "From Lead" field in the Account object is updated with 'Yes' value everytime it's related Parent__c object record is updated with a Child_count__C equal to 2.
 
trigger updateAcct on Parent__c (after update) {

   Set<Id> acid = new Set<Id>();
   
   for(Parent__c temp0:Trigger.New) {
      
      acid.add(temp0.Account__c);
   
   }
   
   Map<Id,Account> act = new Map<Id,Account>([Select Id from Account where Id in :acid]);
  
   Set<Account> acts = new Set<Account>();
   
   List<Account> acts1 = new List<Account>();
   
   for(Parent__c temp:Trigger.New) {
      
      if(temp.child_count__c == 2) {
      
         if(act.containsKey(temp.Account__c)) {
        
            Account upd = act.get(temp.Account__c);
            
            upd.From_Lead__c = 'Yes';
            
            acts.add(upd);
       
         }
      
      }
   
   }
   
   acts1.addAll(acts);
   
   update acts1;

Kindly mark it as an answer if that suffices your requirement.
 
Abhishek BansalAbhishek Bansal
Hi,

Please find your required trigger below and make sure that you have properly replace all the fields with their API name.
trigger updateAccountField on CustomObject__c(before insert, before update){
	Set<id> accIds = new set<id>();
	for(CustomObject__c obj : trigger.new){
		accIds.add(obj.Account__c);//Please replace Account__c with API name of your custom lookup field of Account on custom object.
	}
	Map<Id,Account> accMap = new Map<Id,Account>([Select fieldToUpdate from Account where id IN :accIds]);
	List<Account> accList = new List<Account>();
	for(CustomObject__c obj : trigger.new){
		if(accMap.containsKey(obj.Account__c) && (trigger.isInsert || (trigger.isUpdate && trigger.oldMap.get(obj.id).field__c != obj.field__c))){
			accMap.get(obj.Account__c).fieldToUpdate = obj.field__c;
			accList.add(accMap.get(obj.Account__c));
		}
	}
	if(accList.size() > 0){
		update accList;
	}
}

//Please replace the following variables with their original API name :
//1. CustomObject__c with API name of Custom Object on which you have created Account Lookup Field : Line No. 1, 3 and 8
//2. fieldToUpdate with API name of Account field which you want to update : Line No. 6 and 10
//3. field__c with API name of custom field of that object where account lookup is created : Line NO. 9 and 10

Please do the changes as suggested and let me know if you have any issue.

Thanks,
Abhishek
Francois RouxFrancois Roux
Thnak you very much. May I kindly ask Akhil and Abhishek which method is best and why?
Abhishek BansalAbhishek Bansal
Hi Francois,

We are using triggers here to update the related account.
Both the answers have thier own significance but at the end they both meet your requirement.
I have misseed one thing in my trigger code which i have corrected now.
Please find the updated trigger code below :
trigger updateAccountField on CustomObject__c(after insert, after update){
	Set<id> accIds = new set<id>();
	for(CustomObject__c obj : trigger.new){
		accIds.add(obj.Account__c);//Please replace Account__c with API name of your custom lookup field of Account on custom object.
	}
	Map<Id,Account> accMap = new Map<Id,Account>([Select fieldToUpdate from Account where id IN :accIds]);
	List<Account> accList = new List<Account>();
	for(CustomObject__c obj : trigger.new){
		if(accMap.containsKey(obj.Account__c) && (trigger.isInsert || (trigger.isUpdate && trigger.oldMap.get(obj.id).field__c != obj.field__c))){
			accMap.get(obj.Account__c).fieldToUpdate = obj.field__c;
			accList.add(accMap.get(obj.Account__c));
		}
	}
	if(accList.size() > 0){
		update accList;
	}
}

//Please replace the following variables with their original API name :
//1. CustomObject__c with API name of Custom Object on which you have created Account Lookup Field : Line No. 1, 3 and 8
//2. fieldToUpdate with API name of Account field which you want to update : Line No. 6 and 10
//3. field__c with API name of custom field of that object where account lookup is created : Line NO. 9 and 10

We have to update the values of other object only after the creation and insertion of our record successfully so i have changed the events of trigger from before to after.

Now it depends totally upon you whose method you like the most. :)

Thanks,
Abhishek
Francois RouxFrancois Roux
Akhil, do you have a test for it?
Francois RouxFrancois Roux
Akhil, Do you have a test for it. Francois Private Equity Primary & Secondary Advisory Roux Capital 103, rue de Grenelle - 75007 Paris www.rouxcapital.com +33 1 40 56 94 61 Roux Capital Sarl is registered in France as Conseil en Investissements Financiers (Financial Investment Adviser) under ORIAS number 13000599 on the national Registre Unique des Intermédiaires en Assurance, Banque et Finance and is a valid member of ANACOFI-CIF, regulated by Autorité des Marchés Financiers. This e-mail and any attachment are confidential. They are intended solely for the use of their addressee. If you are not their addressee, please delete them and immediately notify the sender. You must not copy, forward, disclose, print, save, or otherwise use them, or any part of them, in any form.
Akhil AnilAkhil Anil
Hi Francois,

Below is the test class for that trigger with 100% code coverage.
 
@isTest
public class testUpdateAcct {
   
   static testmethod void invokeTrigger() {
      
      Account ac = new Account();
      
      ac.Name = 'Test Account';
      
      Database.SaveResult sr = Database.insert(ac, false);
      
      if(sr.isSuccess()) {

         Parent__c p = new Parent__c();
      
         p.Name = 'Test Parent';      
         
         p.Account__c = sr.getId();
         
         Database.SaveResult sr1 = Database.insert(p, false);
         
         if(sr1.isSuccess()) {
            
            Id pid = sr1.getId();
              
            Parent__c p1 = [Select Id, Name from Parent__c where Id =:pid];
            
            p1.child_count__c = 2;
            
            update p1;
            
            p1.child_count__c = 1;
            
            update p1;
                 
         }        
      
      }
       
   }

}



Thanks,
Akhil
 
This was selected as the best answer
Francois RouxFrancois Roux
Thank you Akhil,
The test gets saved and passed, but the trigger gets Code Coverage 0% in the sandbox. Am I missing something?
Francois
Francois RouxFrancois Roux
Problem: I have written a trigger and a test. In the sandbox, the test saves and passes, but the trigger shows Code Coverage 0%. Can anybody help? Thanks in advance.
Custom object Fundraise__c  has a lookup relationship to Account object and to Fund_c object. The trigger updates FundABC__c, FundDEF__c and Fund__GHI checkbox fields in Account object with 'true' everytime Fundraise__c gets created or updated with field Fund__c equal to FundABC, FundDEF or FundGHI respectively.
 
Trigger:

trigger updateAcct1 on Fundraise__c (after update) {
   Set<Id> acid = new Set<Id>();
   for(Fundraise__c temp0:Trigger.New) {
      acid.add(temp0.Account__c);
   }
   Map<Id,Account> act = new Map<Id,Account>([Select Id from Account where Id in :acid]);
   Set<Account> acts = new Set<Account>();
   List<Account> acts1 = new List<Account>();
   for(Fundraise__c temp:Trigger.New) {
       if(temp.Fund__c == 'FundABC') {
         if(act.containsKey(temp.Account__c)) {
            Account upd = act.get(temp.Account__c);
              upd.FundABC__c = true ;
            acts.add(upd);
         }
      }
       if(temp.Fund_Copy__c == 'FundDEF') {
         if(act.containsKey(temp.Account__c)) {
            Account upd = act.get(temp.Account__c);
              upd.FundDEF__c = true ;
            acts.add(upd);
         }
      }  
      if(temp.Fund_Copy__c == 'FundGHI') {
         if(act.containsKey(temp.Account__c)) {
            Account upd = act.get(temp.Account__c);
              upd.FundGHI__c = true ;
            acts.add(upd);
         }
      }
   }
   acts1.addAll(acts);
   update acts1;
  }
 
Test:
 
@isTest
public class testUpdateAcct1 { 
   static testmethod void invokeTrigger() {
      Account ac = new Account();
      ac.Name = 'Test Account';
      Database.SaveResult sr = Database.insert(ac, false);
      if(sr.isSuccess()) {
         Fundraise__c p = new Fundraise__c();
         p.Name = 'Essai';   
         p.Account__c = sr.getId();
         Database.SaveResult sr1 = Database.insert(p, false);
         if(sr1.isSuccess()) {
            Id pid = sr1.getId();
            Fundraise__c p1 = [Select Id, Name from Fundraise__c where Id =:pid];
            p1.Fund_Copy__c = 'FundABC';
            update p1;
            p1.Fund_Copy__c = 'FundDEF';
            update p1;
            p1.Fund_Copy__c = 'FundGHI';
            update p1;
            p1.Fund__c = '';
            update p1;
         }        
      }
   }
}
Abhishek BansalAbhishek Bansal
Hi Francois,

Please try with below test class :
@isTest
public class testUpdateAcct1 { 
   static testmethod void invokeTrigger() {
      Account ac = new Account();
      ac.Name = 'Test Account';
	  insert ac;
	  
	  Fundraise__c p = new Fundraise__c();
	  p.Name = 'Essai';   
	  p.Account__c = ac.id;
	  insert p;
	  
	  Test.startTest();
	  
	  p.Fund__c = 'FundABC';
	  p.Fund_Copy__c = 'FundGHI';
	  update p;
	  
	  p.Fund_Copy__c = 'FundDEF';
	  update p;
	  
	  Test.stopTest();
	  
    }
}

Let me know if you have any issue.

Thanks,
Abhishek,
Francois RouxFrancois Roux
Hi Abhishek,
I corrected my mistake: only one field, Fund__c, but test does not pass, so I did not even get to the 0 code covered stage. Any suggestion?
Francois
Francois RouxFrancois Roux
Special thanks to Akhil Anil, this works perfectly.