• Ruwantha Lankathilaka
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

Dear all,

 

I am very new to triggers.

I want all opportunities to be automatically submitted for approval if...

 

a) Their Stage is changed to either 'Won' or 'Lost'

b) They are created with the Stage set to 'Won' or 'Lost'

 

What happens based on the below code is that a newly created Oppty with Stage 'Won' or 'Lost' enters approval automatically.

 

When changing the stage to 'won' or 'Lost' on an existing opportunity I get the following error:

There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger OpportunitySubmitForOrderListApproval caused an unexpected exception, contact your administrator: OpportunitySubmitForOrderListApproval: execution of AfterUpdate caused by: System.DmlException: Process failed. First exception on row 0; first error: ALREADY_IN_PROCESS, Cannot submit object already in process.: []: Trigger.OpportunitySubmitForOrderListApproval: line 12, column 1".

 

Moreover creating a new oppty with the Stage NOT set to 'Won' or 'Lost'  brings the following error

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger OpportunitySubmitForOrderListApproval caused an unexpected exception, contact your administrator: OpportunitySubmitForOrderListApproval: execution of AfterUpdate caused by: System.DmlException: Process failed. First exception on row 0; first error: NO_APPLICABLE_PROCESS, No applicable approval process found.: []: Trigger.OpportunitySubmitForOrderListApproval: line 12, column 1". 

 

Any help is greatly apprecated!!! 

Thanks! 

 

trigger OpportunitySubmitForOrderListApproval on Opportunity (after update) {
 
    for (Integer i = 0; i < Trigger.new.size(); i++) {
 
        if (Trigger.old[i].StageName <> '6 - Project won'  ||  Trigger.old[i].StageName <> '7 - Project lost'  &&   Trigger.new[i].StageName == '6 - Project won'  ||  Trigger.new[i].StageName == '7 - Project lost') {
 
            // create the new approval request to submit
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Submitted for approval. Please approve.');
            req.setObjectId(Trigger.new[i].Id);
            // submit the approval request for processing
            Approval.ProcessResult result = Approval.process(req);
            // display if the reqeust was successful
            System.debug('Submitted for approval successfully: '+result.isSuccess());
 
        }
 
    }
 
}