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
SwayampravaSwayamprava 

Creating Approval process using Metadata Api

Hi, I am creating an approval process in apex using meta data API. Approval process is getting created , but workflow action reference not able to get the field update. Getting an error - "
Attempt to de-reference a null object".

Below is the code :
public  with sharing class MetadataServiceCall2 {    
    public static void createApprovalProcess1(){
        
        //start creating approval process , 1st make a call out
        String restUrl = 'callout:ApexMDAPI/services/data/v42.0/limits';
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(restUrl);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        
        //call the metadata service, 2nd part
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = '{!$Credential.OAuthToken}';
        // MetadataService.MetadataPort ms = new MetadataService.createService();
        
        MetadataService.ApprovalProcess approvalProcess = new MetadataService.ApprovalProcess();
        approvalProcess.fullName = 'PDM__c.TestApproval14';
        approvalProcess.label = 'Test Approval14';
        
        MetadataService.ApprovalEntryCriteria entryCriteriaobj = new MetadataService.ApprovalEntryCriteria();
        
        entryCriteriaobj.criteriaItems = new List<MetadataService.FilterItem>();
        MetadataService.FilterItem criteria = new MetadataService.FilterItem();
        criteria.field='PDM__c.Workflow_Name__c';
        criteria.operation='equals';
        criteria.value='UCP:Development:Development:Movies & Minis:Makeover/Format_WF';         
        
        entryCriteriaobj.criteriaItems.add(criteria);
        entryCriteriaobj.booleanFilter='1';
        approvalProcess.entryCriteria =entryCriteriaobj;
        
        approvalProcess.active = false;
        approvalProcess.allowRecall = false;
        approvalProcess.showApprovalHistory = true;
        approvalProcess.recordEditability = 'AdminOnly';
        approvalProcess.finalApprovalRecordLock = false;
        approvalProcess.finalRejectionRecordLock = false;
        approvalProcess.showApprovalHistory = false;        
        
        MetadataService.ApprovalSubmitter submitter = new         MetadataService.ApprovalSubmitter();
        submitter.type_x = 'user';
        submitter.submitter = UserInfo.getUserName();
        
        MetadataService.WorkflowActionReference wfActionReference = new MetadataService.WorkflowActionReference();
        wfActionReference.name='Update_Status_value8';
        wfActionReference.type_x ='FieldUpdate';
        MetadataService.ApprovalAction initialAction = new  MetadataService.ApprovalAction();              
        initialAction.action.add(wfActionReference);
        
        //Add this action to approvalProcess
        approvalProcess.initialSubmissionActions=initialAction;   
        approvalProcess.allowedSubmitters = new List<MetadataService.ApprovalSubmitter> { submitter };
        List<MetadataService.SaveResult> results =service.createMetadata(new MetadataService.Metadata[] { approvalProcess });
        handleSaveResults(results[0]);
    }
    
    
   
    private static void handleSaveResults(MetadataService.SaveResult saveResult){
         
         if(saveResult==null || saveResult.success)
             return;
         // Construct error message and throw an exception
         List<String> messages = new List<String>();
         messages.add((saveResult.errors.size()==1 ? 'Error ' : 'Errors ') + 
                 'occured processing component ' + saveResult.fullName + '.');
        
         for(MetadataService.Error error : saveResult.errors)
             messages.add(error.message + ' (' + error.statusCode + ').' +( error.fields!=null && error.fields.size()>0 ? 
                     ' Fields ' + String.join(error.fields, ',') + '.' : '' ) );
         if(messages.size()>0)
             throw new MetadataServiceExamplesException(String.join(messages, ' '));
     }
    
    public class MetadataServiceExamplesException extends Exception { }
     
}



I am getting error  at below code :
MetadataService.ApprovalAction initialAction = new  MetadataService.ApprovalAction();              
        initialAction.action.add(wfActionReference);

Can anyone please let me know where I am wrong? Why I am getting null pointer error?
ShirishaShirisha (Salesforce Developers) 
Hi Swayam,

Greetings!

I would suggest you to troubleshoot the code by adding debug statements to see,if there is any list which has no records.

Reference:https://help.salesforce.com/HTViewSolution?id=000063739

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
SwayampravaSwayamprava
It  says : wfActionReference is null, as I am adding this and getting a null pointer exception.

MetadataService.ApprovalAction initialAction = new  MetadataService.ApprovalAction();              
        initialAction.action.add(wfActionReference);
SwethaSwetha (Salesforce Developers) 
HI Swayamprava,
I see you posted the same on https://salesforce.stackexchange.com/questions/327042/creating-approval-process-using-metadata-api-in-salesforce-apex?noredirect=1#comment484552_327042 and the fix was to create a list of Initialaction first and add the object there.

Please mark the answer best to close the thread and help others facing the same issue.Thanks