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
CRMDCRMD 

Double Submitting on Auto-Approval Process Trigger. Help?

Hi All, 

 

I'm admittedly new to working with approval processes through APEX, and was hoping that this would be a quick "gotcha" for one of you veterans.  Basically, this code works, but when the criteria is met for submitting an opportunity into the approval process, it submits the record twice at once.  If it's not clear, the trigger firing condition is that the Opportunity field "Close Deal" is either Submit POC Request or Submit to Book.  Thanks for looking!

 

Here's my code:

trigger Submit_for_Approval on Opportunity (after update) {
//public void submitForApproval(Opportunity opp)
    {
    
    List<Approval.ProcessRequest > oppToSentToApproval = new List<Approval.ProcessRequest >();
for( Opportunity updatedOpp : trigger.new )
{
    Opportunity oldOpp = trigger.oldMap.get( updatedOpp.Id );
    if( (updatedOpp.Close_Deal__c == 'Submit to Book' || updatedOpp.Close_Deal__c == 'Submit POC Request' ) && (oldOpp.Close_Deal__c <> 'Submit to Book' || oldOpp.Close_Deal__c <> 'Submit POC Request'))
    {
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
        req1.setComments('Submitting request for approval automatically using Trigger');
        req1.setObjectId( updatedOpp.id );
        oppToSentToApproval.add( req1 );
    }
}

if( !oppToSentToApproval.isEmpty() )
{
    List<Approval.ProcessResult> results = Approval.process( oppToSentToApproval, false );
    for( Approval.ProcessResult aResult : results )
    {
        if( !aResult.isSuccess() )
        {

List<Database.Error> errors = aResult.getErrors();
String errorMsg = '';
for( Database.Error anError : errors )
{
    errorMsg += anError.getMessage();
}

if( trigger.newMap.get( aResult.getEntityId() ) <> NULL )
     trigger.newMap.get( aResult.getEntityId() ).addError( 'Error submitting Approval Request : ' + errorMsg );

        }
    }
}
    
        }}