+ Start a Discussion
Kevin Chiles 930Kevin Chiles 930 

Trigger to Update Opp Line Items from Opportunity

Hello!

I am trying to set an field on the opportunity line items based when a field on the parent gets updated.  However I am running into some issues, and was wondering if anyone can show me where my fall out is?
 
trigger TaxUpdate on Opportunity(after update) {
        // 1

        List<OpportunityLineItem> childRecords = [Select Id, OpportunityId,Name,LineTax__c FROM OpportunityLineItem WHERE OpportunityId IN: Trigger.newMap.keySet()];
         

        // 2

        for(OpportunityLineItem child :childRecords){

            // 3

            if(trigger.isInsert && Opportunity__r.Tax__c != NULL && !child.Name.contains(eN-PRO,Shipping,Training-Adult,AP-WTY-DTLL2,AP-WTY-FRX2)){

                child.LineTax__c = 'Tax';

            }

            // 4

            else if(trigger.isUpdate && child.LineTax__c == Null && trigger.NewMap.get(child.OpportunityId).Tax__c != trigger.OldMap.get(child.OpportunityId).Tax__c){

                child.LineTax__c = 'Tax';

            }

        }

         

        // 5

        if(childRecords.size() > 0)

            update childRecords;

}

 
Best Answer chosen by Kevin Chiles 930
Balaji Chowdary GarapatiBalaji Chowdary Garapati
@Kevin.,

Make the changes as below:
 
trigger TaxUpdate on Opportunity(after update) {

		
		try{
        List<OpportunityLineItem> childRecords = [Select Id,OpportunityId,Name,LineTax__c FROM OpportunityLineItem WHERE OpportunityId IN: Trigger.newMap.keySet()];
         

		
        for(OpportunityLineItem child :childRecords){


              //Im not sure why you were checking if insert and you dont have any insert event specified in trigger events  
			 			  //Contains is a static string method which accepts only one string as parameter
            if(trigger.isInsert && trigger.NewMap.get(child.OpportunityId).Tax__c != NULL && !(child.Name.contains('eN-PRO')||child.Name.contains('Shipping')||child.Name.contains('Training-Adult')||child.Name.contains('AP-WTY-DTLL2')||child.Name.contains('AP-WTY-FRX2'))){

                child.LineTax__c = 'Tax';

            }


            else if(trigger.isUpdate && child.LineTax__c == Null && trigger.NewMap.get(child.OpportunityId).Tax__c != trigger.OldMap.get(child.OpportunityId).Tax__c){

                child.LineTax__c = 'Tax';

            }

        }

         



        if(childRecords.size() > 0)
		update childRecords;
			
			}catch(Exception e){
				system.debug('** ERROR'+e.getMessage()); // Catch any error to debug and see whats the error is about
			}

}
Before modifying the code, review the comments in the code.

Add a debug log and see why it is going wrong. 

For more info on string methods, visit
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm

Hope it helps.,
Thanks,
Balaji