0

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);
        }


    }

}
1

I started to reply to this yesterday, then ran out of time. I hope you find this helpful in learning how to write a trigger for yourself.

Let's start at the beginning of your trigger. There's no need for the initial debug statement before it's done anything. A debug log will show entry into the trigger.

if(Trigger.isInsert)

Even though you've defined your trigger as After Insert, After Update, the above line would apply to both a before insert or an after insert condition.

So, instead, you might want to use:

If(Trigger.isAfter)
   {

   If(Trigger.isInsert)
   {

      .... After insert code
    }

    If(Trigger.isUpdate)
    {
        ...After update code
     }
 }

The above assumes the logic for the two need to be separated in some manner. If it doesn't, then just combine them and put it all in the isAfter or combine the conditions using an && along with parens and a ||. E.G.:

If(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)){

Next, we don't use a try at the beginning of a trigger. Why? Because we have trigger.new and trigger.old that contains the records we want to sort through. We need to determine whether or not they contain records that meet the criteria to cause us to need to run the rest of the code in our trigger.

Additionally, it's always MUCH easier to bulkify a trigger from the beginning than it is to do it afterward. Always think in terms of collections (lists, sets and maps) rather than single records to operate on as you build your trigger.

So the next part of our after insert trigger will be:

List<Id>CtcIds = new list<Id>();

For(opportunity o:trigger.new)
}
   If(o.stage == 'Closed-Won' && trigger.oldmap.get(o.Id) != 'Closed-Won' && o.total_amount__c != null)
   {
       OppIds.add(o.Id);
   }       
}

Now you'll need to use these OppIds to query OpportunityContactRole to get your contactIds and add them to a map<OppId,contactId> that you can use in a For loop that operates on OppId to first create a new contact, assign the existing contactId to it, and the opp amount to your custom field and then add each contact to a list.

After the end of the For loop, update the list of contacts which brings the trigger to a conclusion.

0

You could create this in a Flow. You can replace the button you are using on the Contact.Id from the Contact you are on to insert the ContactId for you to the Opportunity. You could set just the fields you want them to fill out onto your Flow's Screen for the Opportunity. Should be a pretty simple Flow to accomplish this workaround.

You can then also build a Process Builder to do the update of the Amount onto the Contact Associated to the Opportunity when it is marked as Won. No code needed!

0

If you are still looking for a trigger to update the custom field of contact then i have this trigger for you .If any issue then let me know.

trigger opportunitytocontactamountupdate on Opportunity (after insert, after update) {
     if(Trigger.isafter){


        List<contact> thisContact1=new List<contact>();
        set<id> thisContact=new set<id>();
        map<id,id> oppContactMap  = new map<id,id>(); 
        map<id,contact> ContactMap  = new map<id,contact>();

            List<OpportunityContactRole> oppContact = [SELECT id,OpportunityID,ContactId FROM OpportunityContactRole WHERE OpportunityID = :trigger.newmap.keyset() ];
                 system.debug('@@OpportunityContactRole:'+oppContact);
                 if(oppContact.size()>0){

                    for(OpportunityContactRole oppContacObj : oppContact){
                        oppContactMap.put(oppContacObj.OpportunityId,oppContacObj.ContactId);
                        thisContact.add(oppContacObj.Contactid);
                    }
                        for(Contact conObj :[Select Name,Total_Business__c from Contact Where id IN :thisContact] ){
                            ContactMap.put(conObj.id,conObj);
                        }
                            for(opportunity oppObj : trigger.new){
                                ContactMap.get(oppContactMap.get(oppObj.id)).Total_Business__c = oppObj.amount;
                                thisContact1.add(contactMap.get(oppContactMap.get(oppObj.id)));
                            }
                                update thisContact1;
                 }
     }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.