You need to sign in to do that
Don't have an account?
A G Nagaraj
Apex Code for filling Lookup field for two objects while saving
Hi, I have two custom objects Juser & Jpost. In which Juser's field CID & Jpost's field UID has same values. Basing on these two fields, need to fill a lookup relation field for the two objects while saving Jpost record. Plz help.
May I suggest you, please refer to below link from stack exchange community with a similar discussion which might help you.
- https://salesforce.stackexchange.com/questions/27985/save-fields-of-two-objects
Please let us know if this helps.Thanks,
Nagendra
Just to clarify, what type of relation have you made between these two objects? If that is a lookup then you can write a trigger as follows:
Here :
1. There is a Country_Object__c with fields Name, Country__c
2. There is a Lookup relation between Opportunity and Country_Object__c
3. When you associate Opportunity with Country_Object__c the Value from Country__c on Country_Object__C must be copied to Country__c on Opportunity.
Trigger:
trigger Update_Country on Opportunity (before insert, before update) {
set<ID>cObjectID = new set<ID>();
for(Opportunity opp : Trigger.new){
if(opp.Country_Object__c != null){
cObjectID.add(opp.Country_Object__c);
}
}
if(!cObjectID.isEmpty()){
Map<ID,Country_Object__c> cObjectMap = new Map<ID,Country_Object__c>([select Id, Name, <br> Country__c from Country_Object__c where Id IN: cObjectID]);
for(Opportunity opp : trigger.new){
if(cObjectMap.get(opp.Country_Object__c).Country__c != Null){
// fill the country name on Opportunity with Country Name on Country_Object__c
opp.Country__c = cObjectMap.get(opp.Country_Object__c).Country__c;
}
}
}
}
Unit Test:
@isTest
private class TestUpdateCountryOpportunity {
static testMethod void myUnitTest() {
Account a = new Account(Name = 'Berlington');
insert a;
Country_Object__c cObj = new Country_Object__c(Name = 'Object1', Country__c = 'India');
insert cObj;
Opportunity o= new Opportunity ( Name='test',AccountId = a.Id,<br>CloseDate = Date.today(),Amount=1, <br> StageName='1 - Marketing',
Country_Object__c = cObj.Id);
insert o;
Opportunity opp = [select Id, Name, Country__c from Opportunity where Id =: o.Id];
system.assertEquals(opp.Country__c, cObj.Country__c);
}
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Deepali Kulshrestha