+ Start a Discussion
Deepak G 9Deepak G 9 

how to update a custom object custom field with another custom object custom field using trigger in salesforce

HI All,
I have two custom object custom1__c and custom2__c.
on custom1__c i have a field field1__c and
I need to update the value of field1__c to the custom__2's field field2__C.

Could anyone please help.

Thanks in Advance,
Deepak 
Om PrakashOm Prakash
Hi,
In bellow sample code, I am assuming email__c field is available on both object and I am using this email  as a criteria to update object1’s field with object2’s field.
Map<String, String> mapFields = new Map<String, String>();
For(Custom2__c obj : [Select id, email__c, field2__c from Custom2__c]){
     mapFields.put(obj.email__c, obj.field2__c);
}

​for(Custom1__c obj :  Trigger.New){
    If(mapFields.containsKey(obj.email__c)){
        obj.field1__c = mapFields.get(obj.email__c));
   }
}

 
jigarshahjigarshah
Deepak,

There are multiple ways to address your scenario.

1. If there exists a parent child relationship between your custom objects custom1__c and custom2__c, such that custom2__c is the Parent for custom1__c then field1__c can be a custom formula field. Create a cross object formula field on custom1__c that refers the field2__c using the __r relationship. The formula for field1__c as the formula field is as follows.
Custom2__r.Field2__c
2. The other way is to write a process builder or a workflow and use their Field Update action to update the value within field1__c on custom1__c based on a value change within field2 on custom2__c. This will work only when custom2__c is the Parent for custom1__c within a Lookup or a Master Detail relationship.


If both the objects are not related then you will require a after insert and after update Apex trigger to update the value of field1__c on custom1__c when field2__c on custom2__c changes.