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
SURESH NADARAJANSURESH NADARAJAN 

How to update related entity details using a trigger

Dear All,

I am new to Salesforce Apex coding, please provide me sample code for updating related entity details. While updating an Oppurtunity, I need to update the Account details of that Oppurtunity.

Thanks In Advance
Suresh N
Vidhyasagaran MuralidharanVidhyasagaran Muralidharan
Trigger accountupdate on oppurtunity(after insert){
<Account > a = new <account>();
For (oppurtunity o :Trigger.new)
{
a.account name=o.account name;
a.account number=o.account number;
\\other fields you need
}
database.insert(a);
}
this is how the code will look like for your requirement
Hargobind_SinghHargobind_Singh
Here is a sample. You can add your logic to update inside the loop. You should also add some error checking in the code for value not present in map, etc:

trigger TestOpp on Opportunity (after update) {
	Set<ID> accIdSet = new Set<ID>(); 
	for(Opportunity o: trigger.new){
		accIdSet.add(o.AccountId); 
	}
	//retrieve Accounts related to Opportunity.  
	Map<ID, Account> accMap = new Map<Id, Account>([select id, name from Account where id in :accIdSet]);
	//update Account fields
	List<Account> accUpdList = new List<Account>(); 
	for(Opportunity o: trigger.new){
		Account ac1 = accMap.get(o.accountID); 
		ac1.name = 'Some Test Update'; 
		//remove above line and add your update code here 
	 	accUpdList.add(ac1); 
	}
	update accUpdList; 
}


SURESH NADARAJANSURESH NADARAJAN
Dear All,

Thanks for your quick replies..... Here is my final code, which is also working.

trigger Opportunity_AccountUpdateBeforeUpdate on Opportunity (before update) {
    Account acc = new Account();
        for(Opportunity objOpp:Trigger.new) {
        acc.Id = objOpp.AccountId;
        acc.Website = 'www.gmail.com';
   }
   database.update(acc);
}

Hargobind_SinghHargobind_Singh
Hi Suresh, 

Your code will work for one account, but if accounts are updated in bulk, the trigger will fail. Please make your trigger bulk compatible. 


SURESH NADARAJANSURESH NADARAJAN
Hi hs1,

Thanks for your reply, I will follow ur code and modify according to my needs, can u please reply how I can test / check bulk update of accounts.
Hargobind_SinghHargobind_Singh
Hi Suresh,

Here is a sample test class to check Bulk Account and Opportunity Load. You can modify this to add more opportunity to test larger batches as well. You might also want to run a loop to create and add opportunities to a list and then insert. 

@isTest

public with sharing class TestSample1 {
	static testMethod void testOpportunities(){
		List<Account> lstAccount = new List<Account>(); 
		Account acct = new Account(name='test account');
        lstAccount.add(acct); 
		Account acct2 = new Account(name='test account 2');
		lstAccount.add(acct2); 
		//bulk insert Accounts
        insert lstAccount;

		List<Opportunity> lstOpportunity = new List<Opportunity>(); 
        Opportunity opp1 = new Opportunity (Name='Opp1',StageName='Qualified', AccountId = acct.id,closedate=system.today());
        lstOpportunity.add(opp1); 
        Opportunity opp2 = new Opportunity (Name='Opp2',StageName='Qualified', AccountId = acct.id,closedate=system.today());
        lstOpportunity.add(opp1); 
        Opportunity opp3 = new Opportunity (Name='Opp3',StageName='Qualified', AccountId = acct2.id,closedate=system.today());
        lstOpportunity.add(opp1); 
        
        insert lstOpportunity;
	}
}


Sameer PrasonnSameer Prasonn
Hi Suresh,

Vidhyasagaran Muralidharan code doesn't work your need since he has given the approach which work on insert.
Hargobind approach is correct and work on bulk update either.

the best part is hargobinds code keep the SOQL Queries out of the loop which is a standard guideline

Set<ID> accIdSet = new Set<ID>();
// this will fetch all the Ids for Account
for(Opportunity o: trigger.new){
	        accIdSet.add(o.AccountId);
}
//retrieve Accounts related to Opportunity. 
Map<ID, Account> accMap = new Map<Id, Account>([select id, name from Account where id in :accIdSet]);

now onwords we can perform all the operation whatever we want

Well done Hargobind [https://developer.salesforce.com/forums/ForumsProfile?communityId=09aF00000004HMG&userId=005F0000003Fd8p&showHeader=false] .

Keep it up. You rocks.
Sameer PrasonnSameer Prasonn
It would be great if you choose hargobind's answer  as Best Answer !!!
Vijaya Kumar RegantiVijaya Kumar Reganti
Hi,

Please find the below code which describes a trigger on the contact object to update the fields on the account object.

I have done way back.

you can do the same for opportunity also.

Code:
************

trigger ConTrgToUpdateParent on Contact (after update) {

   
    Map<Id,Contact> Mp = new Map<Id,Contact>();
    List<Account> aLstToUpdate = new List<Account>();
   
    //indexed for loop
    for(integer i=0; i<trigger.new.size(); i++){
       
       
        //condition to check if the phone value is changed
        if(trigger.new[i].Phone != trigger.old[i].phone){           
           
            //Adding the Account Id's to a set
            //aIds.add(trigger.new[i].AccountId);
           // System.debug('Mp'+Mp.size()+'----'+Mp);
            System.debug('trigger.old[i].AccountId : '+trigger.old[i].AccountId);
            //System.debug('trigger.new[i] : '+trigger.new[i]);
           
            Mp.put(trigger.old[i].AccountId,trigger.new[i]);           
           
        }
        //Querying the Account records where the contact phone is changed..
        for(Account acc :[Select Id,phone FROM Account WHERE Id =: Mp.keySet()]){          
           
           
            //updating the account phone with the contact changed phone value..
            system.debug('Mp.get(acc.Id) :'+Mp.get(acc.Id));
            acc.phone = Mp.get(acc.Id).phone;
           
            //adding the account with changed phone to a list..
            //update acc;//
            aLstToUpdate.add(acc);
        }
        //updating the account list with new phone values
        update aLstToUpdate;
       
    }
}
Richard BlakeRichard Blake
You were close but you will need to make a list of all the accounts linked to all the opportunitites, then update that list.

trigger Opportunity_AccountUpdateBeforeUpdate on Opportunity (before update) {
   List<Account> accountsToUpdate = new List<Account>();

   for(Opportunity objOpp:Trigger.new) {
        Account acc = new Account();
        acc.Id = objOpp.AccountId;
        acc.Website = 'www.gmail.com';
        accountsToUpdate.add(acc);
   }

   update accountsToUpdate;
}
Richard BlakeRichard Blake
hargobind - your answer is good, but the Account query is unnecessary. If you initialise a new Account and assign the Id of an existing Account then updating it will update the exisitng record.