+ Start a Discussion
Jane NicolasJane Nicolas 

Trigger to update a field with values of other field in other object

Hi
This is Jane here I had a scenario where Feild 1 of A object needs to be updated with same value of  the Field 2 in Object B , whenever an update or insert of Field 2 occurs. I tried following Trigger But it doesn't seem to help. Can anyone suggest ? Thanks.

trigger OpportunityTrigger on Opportunity (after insert, after update)
{
    Set<Id> accountIds = new Set<Id>();
    for(Opportunity opp : Trigger.new)
    {
         accountIds.add(opp.AccountId);
    }

   Map<ID, Account> mapAccounts = new Map<ID, Account>([SELECT Id, Plan_Number__c FROM Account where Id IN :accountIds]);
List<Account> lstAccToUpdate = new List<Account>();
   For(Opportunity opp : Trigger.new)
   {
       Account acc = mapAccounts.get(opp.AccountId);
      acc.Plan_Number__c = opp.Plan_Number__c;
      lstAccToUpdate.add(acc);
   }
  update lstAccToUpdate;
Map<Id, Account> mapUpdatedAccounts = new Map<Id,Account>();
  For(Account acc : lstAccToUpdate)
  {
      mapUpdatedAccounts.put(acc.Id,acc);
  }
  
}
sandeep sankhlasandeep sankhla
Hey Jane,

So when we update or insert opportunty then we should find the related accound and then we should update the accountf feidl with opportunity foeld correct ? please confirm If I am correct..

Thanks
Sandeep
Jane NicolasJane Nicolas
Yes, Almost right. I want each time  field1 is updated or changed in Opp . the corresponding Account gets updated with same value automatically
sandeep sankhlasandeep sankhla
Can you replace these 3 lines with below lines
 Account acc = mapAccounts.get(opp.AccountId);
      acc.Plan_Number__c = opp.Plan_Number__c;
      lstAccToUpdate.add(acc);


replace with below lines
 
if(opp.AccountId != null ) {
Account acc = new Account(Id = opp.AccountId);
acc.Plan_Number__c = opp.Plan_Number__c;
lstAccToUpdate.add(acc);
}


Please check and let me know if it works...

Thanks
Jane NicolasJane Nicolas
Plan Number is still not getting updated in Account..Thanks
Jane NicolasJane Nicolas
Any suggestions will help.
Jane NicolasJane Nicolas
Also to let you know The Account has two Record Types and both has a master detail relationship on Opportunity but field to be updated in Account only exists in one Record Type...If this may be the reason of tRigger not getting through
sandeep sankhlasandeep sankhla
Can you test updating the field for the recordtype for which it is available ?chcek if it is working for that or not s?
Jane NicolasJane Nicolas
Could you elaborate if The Record Types are "abc" and "def"
sandeep sankhlasandeep sankhla
I was telling you to test with the record which is having that field present...update opportunity which is having account and that account recordtype should be the one which is having the field..just to test if it is due to recordtype or not?can you test this or you need more elaboration
Jane NicolasJane Nicolas
I tested it thatways..