I am quite new to Sales force
I need to update a custom field on contact using total_amount_c
when ever any opportunity is created or updated with stage 'Closed-Won'
, opportunity amount value is added up in total_amount_c
,
I tried writing a Trigger for this Scenario but I keep getting the value of OpportunityContactRole = null
since Opportunity ID and ContactID is not inserted in OpportunityContactRole
when Opportunity is created even though I created the Opportunity from the related list shown for the Opportunity in contacts
Trigger Code :
trigger UpdateContactTotalBusiness on Opportunity (after insert, after update) {
System.debug('Start of trigger');
if(Trigger.isInsert)
{
try{
// I Know this is wnot work properly for dataloader , will bulkify it later
Opportunity opp = Trigger.new[0];
System.debug('Getting opptunity trigger');
System.debug('Start Tigger : '+opp.name);
OpportunityContactRole ocr;
Contact contact;
if(opp !=null ){
ocr = [Select o.SystemModstamp, o.Role, o.OpportunityId, o.LastModifiedDate,
o.LastModifiedById, o.IsPrimary,o.IsDeleted, o.Id, o.CreatedDate, o.CreatedById, o.ContactId
From OpportunityContactRole o where IsPrimary = true and o.OpportunityId =: opp.id];
System.debug(opp.name+' '+opp.amount);
System.debug(ocr.id);
if(ocr != null ){
contact = [Select c.OwnerId, c.Id, c.AccountId,c.name,c.total_business__c From Contact c where c.id =: ocr.ContactId ];
if(opp.StageName=='Closed Won' && opp.amount !=null && opp.amount != 0)
{
contact.total_business__c += opp.amount;
System.debug('Contact Total Bussniess : '+contact.total_business__c);
update contact;
}
}
}
}
catch(System.Exception exp)
{
System.debug(''+exp);
}
}
}