Tuesday, July 4, 2017

Trigger Scenario in Salesforce: 

Auto populate a custom Text field "Account_Name__C " on opportunity product lineitem with an "Account Name" from the opportunity object or possibliy from Account Object itself, needs to happen when a user selects the opportunity product and saves the record.


Using the After trigger:
trigger updateOLI on OpportunityLineItem (after insert) {
      List<OpportunityLineItem> OpportunitiesToUpdate = new List<OpportunityLineItem>();
      for(OpportunityLineItem OLI : [Select Id, Opportunity.Account.Id From OpportunityLineItem Where Id IN : trigger.newMap.keyset()]) {
            OLI.Account_Name__c = OLI.Opportunity.Account.Name;
             OpportunitiesToUpdate.add(OLI);            
       }   
       if(!OpportunitiesToUpdate.isEmpty())
                update OpportunitiesToUpdate;
}
Using the before trigger:
trigger updateOLI on OpportunityLineItem (Before insert ,before update) {

for(OpportunityLineItem oli : trigger.new){
                oppids.add(oli.OpportunityId);
            }
            map<id,opportunity> mapopp = new map<id,opportunity>([select id,name,accountid,account.name                                                                                    from opportunity where id IN:oppids]);
            for(OpportunityLineItem oli1 : trigger.new){
              
                    if(mapopp.containsKey(oli1.OpportunityId)){
                        oli1.Account_Name__c = mapopp.get(oli1.opportunityid).Account.name;
                    }
}

           }

No comments:

Post a Comment