You need to sign in to do that
Don't have an account?
Can't set household on Opportunity trigger
Hi,
I'm trying to add a trigger to set a lookup field in Opportunity to point back to the Household. I'm using 1x1 contact model. To get to Household from Opportunity, I tried to:
- get the Account from Opportunity
- get the Contact from Account (since this is 1x1 model)
- get the Household from Contact
The trigger code is pretty simple, but somehow the Account and Contact fields are always NULL. Could you please help?
trigger setHouseholdOnOpportunity on Opportunity (before insert) {
for (Opportunity opp : trigger.new) {
System.debug('Account is ' + opp.Account);
System.debug('Contact is ' + opp.Account.npe01__One2OneContact__c);
if ((opp.Account != NULL) && (opp.Account.npe01__One2OneContact__c != NULL)) {
System.debug('Contacts household is ' + opp.Account.npe01__One2OneContact__r.npo02__Household__c);
opp.OppHousehold__c = opp.Account.npe01__One2OneContact__r.npo02__Household__c;
System.debug('SetHouseholdOnOpp Opp Household is ' + opp.OppHousehold__c);
update opp;
}
}
}
Thanks. Thu :-)
in the opportunity trigger you will be able to get the account id information if you want any thing more from account you should query to get the same...
Hi Kiran,
for (Opportunity opp : trigger.new) {
Account a = [SELECT npe01__One2OneContact__c FROM Account WHERE Id =: opp.Account.Id];
System.debug('Account is ' + a);
Contact c = [SELECT npo02__Household__c FROM Contact WHERE Id =: a.npe01__One2OneContact__r.Id];
System.debug('Contact is ' + c);
if ((opp.Account != NULL) && (opp.Account.npe01__One2OneContact__c != NULL)) {
System.debug('Contacts household is ' + opp.Account.npe01__One2OneContact__r.npo02__Household__c);
opp.OppHousehold__c = opp.Account.npe01__One2OneContact__r.npo02__Household__c;
System.debug('SetHouseholdOnOpp Opp Household is ' + opp.OppHousehold__c);
update opp;
}
}and the Apex class:@isTest
private class setHouseholdOnOpportunityTest {
static testMethod void testSetHouseholdOnOpportunity () {
Contact c = new Contact(LastName='Bar', FirstName='Foo');
insert c;
System.debug('Contact ID is ' + c.id);
Campaign cp = new Campaign(Name='General Donations');
insert cp;
Opportunity o = new Opportunity(Name='Test01',CloseDate=date.parse('1/1/2010'),StageName='Received',Amount=10);
o.Campaign=cp;
Test.startTest();
insert o;
System.debug('Opportunity ID is ' + o.id);
// retrieve the opportunity and check the household field
Opportunity newo = [SELECT OppHousehold__c FROM Opportunity WHERE Id =:o.Id];
System.debug('Household on Opp is ' + newo.OppHousehold__c);
// retrieve the household from contact
Contact newc = [SELECT npo02__Household__c FROM Contact WHERE Id =:c.Id];
System.debug('Household on Contact is ' + newc.npo02__Household__c);
// Check that the trigger correctly set the household on opp same as contact
System.assertEquals(newc.npo02__Household__c, newo.OppHousehold__c);
Test.stopTest();
}
}