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
Akshay ShrivastavaAkshay Shrivastava 

How to update field of one object with another object field

I had 2 objects with 3 fields in each..
now i want if the first 2 field  of  object2 is same as object1 then the 3rd field of object2 is updated same as object1 3rd field.User-added image
Best Answer chosen by Akshay Shrivastava
Suraj Tripathi 47Suraj Tripathi 47

Hi Akshay,

Please check the below code.

Scenario: when contact 2 fields are the same as that of their account field then contact third field data automatically goes into the account third field.

trigger DataUpdate on Contact (before update) {
if(trigger.isBefore && Trigger.isUpdate){
set<Id> accountSet=new set<Id>();
	for(contact con:trigger.new){
	accountSet.add(con.accountid);
	}
	
	Map<Id,Account> accountMap=new Map<Id,Account>([select id,class__c,city__c,Location__c from Account where id in: accountSet]);
	
	for(contact con:trigger.new){
	if(con.accountid==accountMap.get(con.accountid).id){
	if( con.class__c==accountMap.get(con.accountid).class__c && con.city__c==accountMap.get(con.accountid).city__c){
	accountMap.get(con.accountid).Location__c=con.Location__c;
	}
	
	}
	
	}
	update accountMap.values();
}
}


If it helps you please mark it as Best Answer.

Thank You!

All Answers

SwethaSwetha (Salesforce Developers) 
HI Akshay,
The code snippet from https://salesforce.stackexchange.com/questions/152993/trigger-to-update-field-values-from-another-object should help you get started. 

Similar ask:https://developer.salesforce.com/forums/?id=906F000000093zwIAA

If this information helps, please mark the answer as best. Thank you
Suraj Tripathi 47Suraj Tripathi 47

Hi Akshay,

Please check the below code.

Scenario: when contact 2 fields are the same as that of their account field then contact third field data automatically goes into the account third field.

trigger DataUpdate on Contact (before update) {
if(trigger.isBefore && Trigger.isUpdate){
set<Id> accountSet=new set<Id>();
	for(contact con:trigger.new){
	accountSet.add(con.accountid);
	}
	
	Map<Id,Account> accountMap=new Map<Id,Account>([select id,class__c,city__c,Location__c from Account where id in: accountSet]);
	
	for(contact con:trigger.new){
	if(con.accountid==accountMap.get(con.accountid).id){
	if( con.class__c==accountMap.get(con.accountid).class__c && con.city__c==accountMap.get(con.accountid).city__c){
	accountMap.get(con.accountid).Location__c=con.Location__c;
	}
	
	}
	
	}
	update accountMap.values();
}
}


If it helps you please mark it as Best Answer.

Thank You!

This was selected as the best answer