function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
pmozz01pmozz01 

Urgent help for trigger in production - How to add Opportunity isClosed requirements to trigger

My trigger is working the way I need it to EXCEPT I need to exclude opportunities that are closed from being updated regardless of the values of the workorder.  I cannot figure out how to include this.  This trigger is already in production and I urgently need to correct the issue as it is updating opportunities that were marked closed-won to the stage of job compled!  Any suggestions?

 

 

Trigger CheckOpportunityWorkorders on Work_Order__c (before insert, before update) {

    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>();
	
    Set<Id> oppIds = new Set<Id>();
	 if(Trigger.isInsert || Trigger.isUpdate)
    //Store Opportunity Id for each Work_Order__c
    for(Work_Order__c workOrder : Trigger.new)
    {
       if (workOrder.stage__c == 'Work Order Closed - Quickbooks' ||  workOrder.stage__c == 'Job Completed' ) 
       
       
       oppIds.add(workOrder.Opportunity__c);
    }
    
	if(oppIds.size() > 0)
	{
		//Retrieve all the Opportunities and related Work Orders regardless the status
		List<Opportunity> opportunities = new List<Opportunity> ([SELECT Id, StageName, (SELECT Id, Opportunity__c, Stage__c FROM Work_Orders__r) FROM Opportunity WHERE Id IN :oppIds]);

		for (Opportunity opportunity : opportunities) {

			Boolean allCompleted = true;
			for(Work_Order__c workOrder:opportunity.Work_Orders__r)
			{	if(workOrder.stage__c != 'Work Order Closed - Quickbooks' && workOrder.stage__c != 'Job Completed')
				{					
					allCompleted = false;
					break;
				}
			}
			
			if(allCompleted == true) 
			{
				opportunity.StageName = 'Job Completed';
				opportunitiesToUpdate.add(opportunity);
			}
		}
	}
	
	if(opportunitiesToUpdate.size() > 0) 
	update opportunitiesToUpdate;
	
}

 

 

_Prasu__Prasu_

I think adding a where clause in the Query of opportunity should solve your problem.

 

[SELECT Id, StageName, (SELECT Id, Opportunity__c, Stage__c FROM Work_Orders__r) FROM Opportunity WHERE Id IN :oppIds and StageName ! = 'closed-won']