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
NecroGigglesNecroGiggles 

submit opportunity for approval when stage is updated

I am trying to write a trigger that will send a Opportuinty to approval when the stage is set to "send to accountig" I dot get a error when I save the code but it does not work and I am not sure why. 

trigger OpportunitySubmitForApproval2 on Opportunity (after update) {

for (Opportunity opp : Trigger.new){

if (opp.Stagename =='Sent To Accounting'){
    Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
    
}
}
}
 
Best Answer chosen by NecroGiggles
Crystal Rochlitz 4Crystal Rochlitz 4
for (Opportunity opp : Trigger.new){

	if (opp.Stagename =='Sent To Accounting'){
		Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
			req.setComments('Submitted for approval.');
			req.setObjectId(opp.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());
    }
}

Try that. Also, here is a link with a little walk through and some discussion on the topic: http://blog.jeffdouglas.com/2010/01/04/automating-salesforce-approval-processes-with-apex-triggers/

All Answers

Crystal Rochlitz 4Crystal Rochlitz 4
You need to pass the Ids of the opportunities to the approval process:   req.setObjectId(opp.Id)... Check this for a complete example
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_process_example.htm
NecroGigglesNecroGiggles
I guess I am still missing something. Code looks like this now no error no saving but still does not work 
trigger OpportunitySubmitForApproval2 on Opportunity (after update) {

 for (Opportunity opp : Trigger.new){

if (opp.Stagename =='Sent To Accounting'){
    Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
    req.setObjectId(opp.Id);
    
 
Crystal Rochlitz 4Crystal Rochlitz 4
for (Opportunity opp : Trigger.new){

	if (opp.Stagename =='Sent To Accounting'){
		Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
			req.setComments('Submitted for approval.');
			req.setObjectId(opp.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());
    }
}

Try that. Also, here is a link with a little walk through and some discussion on the topic: http://blog.jeffdouglas.com/2010/01/04/automating-salesforce-approval-processes-with-apex-triggers/
This was selected as the best answer