Salesforce Metadata API

data-backup-256What is Metadata ?

First you need to understand data. What is data in context with Salesforce. Data is anything which is stored in a database like records related to Contacts,  Accounts, Leads Opportunity etc.

Metadata : Metadata can be defined as the set of data about another data. i.e., Configuration/Code/Logic of the underlying structure which is used to store the data (Records). Another definition is you can say the database structure in which you will be saving the data.  Metadata Api for Salesforce can do several things programmatically.

meta data

                                        Meta Data

Some of the tasks are mentioned below:

You can read, create, update, delete following components in a Salesforce organization.

  1. Custom Objects/Fields.
  2. Visualforce pages.
  3. Page Layouts.
  4. Validation rules.
  5. Apex.
  6. Workflows.
  7. Approval processes.
  8. Profiles.
  9. Reports etc.
  10. Security.

                  You can configure a Salesforce organization just by running a piece of code. It means that you can create Objects,Fields,Validation,Workflows, Profiles, Reports for a particular client organization just by running the piece of code so that you need not do all the customisation settings manually which will consume time if you have to do that several times for different clients for the same configuration settings. You can also take the backup of your organization customisation settings just by fetching the metadata WSDL from your Salesforce org. For this You need to click setup>type API-Click on API >Click Generate metadata WSDL and download the xml file.

There are two types of Metadata Api calls:

  1. Synchronous – This will give the result immediately as soon as you call a method.
  2. Asynchronous – This will not give result immediately, it will take time.

asynAsynchronous : There are four types of methods which we can use:

  1. Create();  
  2. Update();
  3. Upsert();
  4. Delete();

We will discuss only for synchronous method.

Synchronous-iconSynchronous : There are five types of methods which we can use:

(i) createMetadata();

saveResult[] = metadataConnection.createMetadata(Metadata[] metadata);

(ii) readMetadata();

readResult = metadataConnection.readMetadata(string metadataType, string[] fullNames);

(iii)updateMetadata();

saveResult[] = metadataConnection.updateMetadata(Metadata[] metadata);

(iv)upsertMetadata();

spsertResult[] = metadataConnection.upsertMetadata(Metadata[] metadata);

(v)deleteMetadata();

seleteResult[] = metadataConnection.delete(string metadataType, string[] fullNames);

All these classes saveResult, readResult, upsertResult, deleteResult comes from a main class that is MetadataService.cls in which all the relevant methods are present to function Read, Create, Update, Upsert or Delete properly.

Now I will demonstrate how to create Custom components.

You can use following methods to create components:

(A) To Create a Custom Object:

You need to add this code to your class which you are using and call this method via class name to create the object. Note: MetadataService is also a class which have several methods and used in these methods.

Create a Custom Object:

public static void createObject() {

     MetadataService.MetadataPort service = createService();

     MetadataService.customObject customObject = new MetadataService.customObject();

     customObject.fullName = ‘Test__c’;

     customObject.label = ‘Test’;

     customObject.pluralLabel = ‘Tests’;

     customObject.nameField = new MetadataService.CustomField();

     customObject.nameField.type_x = ‘Text’;

     customObject.nameField.label = ‘Test Record’;

     customObject.deploymentStatus = ‘Deployed’;

     customObject.sharingModel = ‘ReadWrite’;

     List<MetadataService.SaveResult> results =

     service.createMetadata(

     new MetadataService.Metadata[] { customObject });

     handleSaveResults(results[0]);

   }

So now if you want to create the object then you just have to call this method like this:

YourClassName.createObject();

If you face some problem like : Remote site settings error. Then just create a remote site setting in your org by typing remote site settings in setup and configure it and click save.

As you call this method like for example in the Execute Anonymous section then it will create an object named as Test.

(B) To Upsert a Custom Object:

Upsert a Custom Object

public static void upsertObject() {

       MetadataService.MetadataPort service = createService();

       MetadataService.CustomObject customObject = new MetadataService.CustomObject();

       customObject.fullName = ‘Test__c’;

       customObject.label = ‘Test’;

       customObject.pluralLabel = ‘Tests Upsert’;

       customObject.nameField = new MetadataService.CustomField();

       customObject.nameField.type_x = ‘Text’;

       customObject.nameField.label = ‘Test Record Upsert’;

       customObject.deploymentStatus = ‘Deployed’;

       customObject.sharingModel = ‘ReadWrite’;

       List<MetadataService.UpsertResult> results = service.upsertMetadata(new MetadataService.Metadata[]

{ customObject });

   handleUpsertResults(results[0]);

   }

(C) To Create a Custom Field:

Create a Custom Field

public static void createField() {

       MetadataService.MetadataPort service = createService();

       MetadataService.CustomField customField = new MetadataService.CustomField();

       customField.fullName = ‘Test__c.TestField__c’;

       customField.label = ‘Test Field’;

       customField.type_x = ‘Text’;

       customField.length = 42;

       List<MetadataService.SaveResult> results =service.createMetadata(new MetadataService.Metadata[] {             customField });

       handleSaveResults(results[0]);

   }

(D) To Delete the above Field:

Delete the above Field:

public static void deleteField()

   {

       MetadataService.MetadataPort service = createService();

       List<MetadataService.DeleteResult> results =service.deleteMetadata(‘CustomField’, new String[] {    ‘Test__c.TestField__c’ });

       handleDeleteResults(results[0]);

   }

(E) To Update the Field:

Update the Field

public static void updateField() {

       MetadataService.MetadataPort service = createService();

       MetadataService.CustomField customField = new MetadataService.CustomField();

       customField.fullName = ‘Test__c.TestField__c’;

       customField.label=’New Test Field Label’;

       customField.type_x = ‘Text’;

       customField.length = 52;

       List<MetadataService.SaveResult> results = service.updateMetadata(new MetadataService.Metadata[] { customField });

       handleSaveResults(results[0]);

   }

(F) To Update Field Level Security:

Update Field Level Security

public static void updateFieldLevelSecurity() {

       MetadataService.MetadataPort service = createService();

       MetadataService.Profile admin = new MetadataService.Profile();

       admin.fullName = ‘Admin’;

       admin.custom = false;

       MetadataService.ProfileFieldLevelSecurity fieldSec = new MetadataService.ProfileFieldLevelSecurity();

       fieldSec.field=’Test__c.TestField__c’;

       fieldSec.editable=true;

       admin.fieldPermissions  = new MetadataService.ProfileFieldLevelSecurity[] {fieldSec} ;

       List<MetadataService.SaveResult> results = service.updateMetadata(new MetadataService.Metadata[] { admin    });

       handleSaveResults(results[0]);

   }

(G) To Update a Custom App:

Update a Custom App

public static void updateCustomApplication() {

       MetadataService.MetadataPort service = createService();

       MetadataService.CustomApplication customApp = (MetadataService.CustomApplication)              service.readMetadata(‘CustomApplication’, new String[] { ‘Test_Application’ }).getRecords()[0];

       customApp.defaultLandingTab = ‘Test_Tab__c’;

      List<MetadataService.SaveResult> results =service.updateMetadata(new MetadataService.Metadata[]    {customApp });

     handleSaveResults(results[0]);

   }

(H) To Create a Page:

Create a Page

public static void createPage() {

       MetadataService.MetadataPort service = createService();

       MetadataService.ApexPage apexPage = new MetadataService.ApexPage();

       apexPage.apiVersion = 25;

       apexPage.fullName = ‘test’;

       apexPage.label = ‘Test Page’;

       apexPage.content = EncodingUtil.base64Encode(Blob.valueOf(‘<apex:page/>’));

       List<MetadataService.SaveResult> results =service.createMetadata(new MetadataService.Metadata[] { apexPage        });

       handleSaveResults(results[0]);

   }

(I) To Create Approval Processes:

Create Approval Processes

public static void createApprovalProcess() {

       MetadataService.MetadataPort service = createService();

       MetadataService.ApprovalProcess approvalProcess = new MetadataService.ApprovalProcess();

       approvalProcess.fullName = ‘Test__c.TestApproval’;

       approvalProcess.label = ‘Test Approval’;

       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();

       approvalProcess.allowedSubmitters = new List<MetadataService.ApprovalSubmitter> { submitter };

       List<MetadataService.SaveResult> results = service.createMetadata(new MetadataService.Metadata[] {    approvalProc

   }

(J) To Read a Report:

Read a Report

public static void readReport() {

MetadataService.MetadataPort service = createService();

MetadataService.Report report =(MetadataService.Report) service.readMetadata(‘Report’,new String[] { ‘MyFolder/MyReport’ }).getRecords()[0];

System.debug(report.description); }

DragnDrop-New-Logo-200x200

I am sharing few of the Meta Data code samples from our most liked app on appexchange. Please click here to install this app.

imagesSample Custom Code:

For creation of a Visualforce page.

Create Visualforce Page

public static void createPage(List objectApiList ) {

try {

System.debug(‘—>>>>In CreatePage–>>>>objectApiList’+objectApiList);

MetadataService.Metadata[] pageList = new list();

MetadataService.MetadataPort service = createService();

for(String str : objectApiList ){

MetadataService.ApexPage apexPage = new MetadataService.ApexPage();

apexPage.apiVersion = 25;

String nameSpace12 = Utility.provideNameSpace();

System.debug(‘—->>>> Starting str=’+str);

str = str.remove(nameSpace12);

// if(str != null && str.equalsIgnoreCase(‘Case’)){

// apexPage.content = EncodingUtil.base64Encode(Blob.valueOf(”));

// }

else

//Commented below line only for unmanaged package

//apexPage.content = EncodingUtil.base64Encode(Blob.valueOf(”));

apexPage.content = EncodingUtil.base64Encode(Blob.valueOf(”));

System.debug(‘—>>>>apexPage.content=’+apexPage.content);

if(str.endsWith(‘__c’)){

str = Utility.removeUnderscore(str);

}

System.debug(‘—>>>>1) str=’+str);

//str = str.remove(nameSpace12);

System.debug(‘—>>>>2) str=’+str);

if(str.contains(‘__’)){ str = str.replaceAll(‘__’ , ‘_’);

}

System.debug(‘—>>>>3) str=’+str);

//apexPage.fullName = nameSpace12+’DragNDrop_’+str ;

apexPage.fullName = ‘DragNDrop_’+str ;

System.debug(‘—>>>>apexPage.fullName=’+apexPage.fullName);

//apexPage.label = nameSpace12+’DragNDrop_’+str ; apexPage.label = ‘DragNDrop_’+str ;

System.debug(‘—>>>>apexPage.label=’+apexPage.label);

pageList.add(apexPage);

System.debug(‘—>>>>ApexPage=’+apexPage);

}

List results = service.createMetadata(pageList);

list str; if(!test.isRunningTest()) handleSaveResults(results[0]);

System.debug(‘—>>>>Page Create Result = ‘ + results);

}

catch(Exception e) { System.debug(‘—->>>createPage Exception = ‘ + e);

}

}

 For Retrieving Page layout information on which you want to add the Page:

Retrieve Page layout information on which you want to add the Page

public static map<String , List<MetadataService.FileProperties>> listMetadata(List<String> objectApiList)

   {

map<String , list<MetadataService.FileProperties>> objectApiNameVsLayoutNameList = new map<String ,     list<MetadataService.FileProperties>>();

list<String> layoutFieldNames = new list<String>();

MetadataService.MetadataPort service = createService();     

List<MetadataService.ListMetadataQuery> queries = new List<MetadataService.ListMetadataQuery>();        

MetadataService.ListMetadataQuery queryWorkflow = new MetadataService.ListMetadataQuery();

queryWorkflow.type_x = ‘Layout’;

queries.add(queryWorkflow);     

MetadataService.FileProperties[] fileProperties = service.listMetadata(queries, 25);

if(test.isRunningTest()){

fileProperties = new list<MetadataService.FileProperties>();  

 fileProperties.add(new MetadataService.FileProperties());

 for(MetadataService.FileProperties fileProperty : fileProperties){

 fileProperty.fullName = ‘Account-‘;

           }

       }

if(fileProperties  != null){

 for(MetadataService.FileProperties fileProperty : fileProperties){

 String nameSpace12 = Utility.provideNameSpace();

 for(String objectApiName : objectApiList){

 nameSpace12 = Utility.provideNameSpace();

 System.debug(fileProperty.fullName);

 System.debug(fileProperty);

 if(fileProperty.namespacePrefix != null && fileProperty.namespacePrefix != ”){

  if(nameSpace12 == fileProperty.namespacePrefix+’__’){

  objectApiName = objectApiName.remove(namespace12);

  }

 namespace12  = fileProperty.namespacePrefix+’__’;

 }

 if(fileProperty.fullName.startsWith(objectApiName+’-‘))

{

layoutFieldNames.add(fileProperty.fullName);

if(objectApiNameVsLayoutNameList.containsKey(objectApiName))

{

List<MetadataService.FileProperties> strList = objectApiNameVsLayoutNameList.get(objectApiName);

String layoutName =  fileProperty.fullName.substringAfter(objectApiName+’-‘);

if(fileProperty.namespacePrefix != null && fileProperty.namespacePrefix != ”)

{

 nameSpace12  = fileProperty.namespacePrefix+’__’;

 }

layoutName  = nameSpace12  + layoutName;

String changedLayoutNow =  objectApiName+’-‘ +  layoutName  ;

System.debug(‘@@@@@@@@@@@@@@@@@@’+changedLayoutNow);    

strList.add(fileProperty );

objectApiNameVsLayoutNameList.put(objectApiName , strList);

 }

 else

{

List<MetadataService.FileProperties> strList = new list<MetadataService.FileProperties>();

String layoutName =  fileProperty.fullName.substringAfter(objectApiName+’-‘);

if(fileProperty.namespacePrefix != null && fileProperty.namespacePrefix != ”)

{

nameSpace12  = fileProperty.namespacePrefix +’__’;

 }

layoutName  = nameSpace12  + layoutName;

String changedLayoutNow =  objectApiName+’-‘ +  layoutName  ;

 System.debug(‘@@@@@@@@@@@@’+changedLayoutNow);

  strList.add(fileProperty );

  objectApiNameVsLayoutNameList.put(objectApiName , strList);

                    }

                   }

               }

            }

        }

 System.debug(objectApiNameVsLayoutNameList + ‘@@@@@@@@@@@@@@@@’);

 return objectApiNameVsLayoutNameList;

   }

   // Retrieving layout

   public static void listMetadataForStart(List<String> objectApiList)

   {

      map<String , list<String>> objectApiNameVsLayoutNameList = new map<String , list<String>>();

       list<String> layoutFieldNames = new list<String>();

       MetadataService.MetadataPort service = createService();   

       MetadataService.CustomField customField = new MetadataService.CustomField();

       customField.fullName = ‘Account.DragDrop_CaAnalogy_Important__c’;

       customField.label = ‘Drag n Drop Important Field’;

       customField.type_x = ‘Text’;

       customField.description = ‘Dont Delete this field. Important For DRAG n DROP FEATURE.’;

       customField.length = 42;

       List<MetadataService.SaveResult> results =service.createMetadata(

       new MetadataService.Metadata[] { customField });                

       if(!test.isRunningTest())

        handleSaveResults(results[0]);

        String nameSpace = ‘null’;

        if(!Test.isRunningTest()){

       MetadataService.CustomObject customObject =(MetadataService.CustomObject)         service.readMetadata(‘CustomObject’,

         new String[] { ‘Account’ }).getRecords()[0];

       for(MetadataService.CustomField field : customObject.fields)

{

if(field != null && field.fullname != null && field.fullname.endsWith(‘DragDrop_CaAnalogy_Important__c’))

{

   String s =field.fullname.substring(0  , field.fullname.indexof(‘DragDrop_CaAnalogy_Important__c’));

    if(s != null && s != ”){

    namespace  = s;

   namespace = namespace.remove(‘__’);

               }

           }

         }

       }    

       System.debug(‘@@@@@@@@@’+namespace);

       if(nameSpace != null){

        namespace = ”== namespace ?’null’:namespace;

        list<Namespace_Prefix__c> listToDelete = new list<Namespace_Prefix__c>();

        list<Namespace_Prefix__c> listToInsert = new list<Namespace_Prefix__c>();

        if(Namespace_Prefix__c.getAll() != null && !Namespace_Prefix__c.getAll().isEmpty()){

        for(String str : Namespace_Prefix__c.getAll().keyset()){

        if(str == nameSpace){

        break;

                   }

else

{

        listToInsert.add(new Namespace_Prefix__c(name = namespace));

        listToDelete.add(Namespace_Prefix__c.getAll().geT(str));

                   }

               }

          }

else

    {

        listToInsert.add(new Namespace_Prefix__c(name = namespace));

        if(!listToDelete.isEMpty())

        delete listToDelete;

         if(!listToInsert.isEmpty())

         insert listToInsert;

      }    

   }

For updating the Page layout by adding the Visualforce page on a newly created Section via code:

Update the Page layout by adding the Visualforce page on a newly created Section via code

  public static map<String , String > updatePageLayouts(map<String , list<String>>        objectApiNameVsLayoutNameList){

  try{

         String nameSpace12 = Utility.provideNameSpace();

          System.debug(‘—>>>In updatePageLayouts’);

          System.debug(‘—>>>Map objectApiNameVsLayoutNameList=’+objectApiNameVsLayoutNameList);

          map<String , String > objectApiNameVRelatedList = new map<String , String > ();

          MetadataService.MetadataPort service = createService();

          List<MetadataService.Metadata> layouyListToBeUpdated = new list<MetadataService.Metadata>();

          for(String str : objectApiNameVsLayoutNameList.keyset()){

          System.debug(‘—->>>>>In for loop str=’+str);

          MetadataService.LayoutItem layoutItemObject = new MetadataService.LayoutItem();

          String stri1 = str;

           layoutItemObject.behavior = ‘Edit’;

           //layoutItemObject.page_x = nameSpace12 +’DragNDrop_’+stri1;//page api name

            String newStr = Utility.removeUnderscore(stri1);

            layoutItemObject.page_x = ‘DragNDrop_’+newStr.remove(nameSpace12);//page api name

            layoutItemObject.width= ‘100%’;

            layoutItemObject.showScrollbars = false;

             layoutItemObject.height  = 300;

             System.debug(‘—>>>>layoutItemObject=’+layoutItemObject);

            MetadataService.LayoutColumn layoutCol = new MetadataService.LayoutColumn ();

            layoutCol.layoutItems =  new MetadataService.LayoutItem[] { layoutItemObject};

            System.debug(‘—>>>layoutCol=’+layoutCol);

            MetadataService.LayoutSection newLayoutObject = new MetadataService.LayoutSection();

            newLayoutObject.customLabel =false;//’Drag and DROp’;

            newLayoutObject.label  = ‘Drag & Drop Section’;

            newLayoutObject.detailHeading = true;

            newLayoutObject.style = ‘OneColumn’;

            list<string> stringTemp = new list<String>();

            System.debug(‘–>>>Layout Section newLayoutObject=’+newLayoutObject);

            System.debug(‘—->>>>>’+objectApiNameVsLayoutNameList);

            System.debug(‘—>>>>>objectApiNameVsLayoutNameList=’ + objectApiNameVsLayoutNameList);

             newLayoutObject.layoutColumns =new MetadataService.LayoutColumn[] { layoutCol};

             System.debug(‘–>>>Layout Section with column newLayoutObject=’+newLayoutObject);

             List<MetadataService.Layout> layoutList =  (List<MetadataService.Layout>) service.readMetadata(‘Layout’, objectApiNameVsLayoutNameList.get(str)).getRecords();

              for(MetadataService.Layout layout : layoutList ){

              System.debug(‘—>>>In for loop layout=’+layout);

              List<MetadatAService.RelatedListItem>tempList = new list<MetadatAService.RelatedListItem>();

              List<MetadatAService.RelatedListItem> saveRelatedList = new list<MetadatAService.RelatedListItem>();

             System.debug(‘—>>>>> before removing layout.relatedLists =’+layout.relatedLists);

             saveRelatedList = layout.relatedLists;

             layout.relatedLists = tempList;

             System.debug(‘—>>>>> layout.relatedLists = ‘ + layout.relatedLists);

             if(layout.layoutSections==null)

             layout.layoutSections= new List<MetadataService.LayoutSection>();

             //layout.layoutSections.add(newLayoutObject);

            layout.layoutSections.add(newLayoutObject);

           layout.relatedLists = saveRelatedList;

           layouyListToBeUpdated.add(layout);

          System.debug(‘—>>>>layouyListToBeUpdated–>>>’+layouyListToBeUpdated);

           }

          }

        handleSaveResults(service.updateMetadata(layouyListToBeUpdated )[0]);

        System.debug(‘—>>>>objectApiNameVRelatedList=’+objectApiNameVRelatedList);

       return objectApiNameVRelatedList;

         }

      catch(Exception e){

      System.debug(e.getMessage() + e.getLineNumber());

      return null;

      }

 }

For Deleting Updated Page Layouts:

Deleting Updated Page Layouts

public static void deleteUpdatePageLayouts(map<String , list<String>> objectApiNameVsLayoutNameList){

  try{

     System.debug(‘—>>>>In deleteUpdatePageLayouts(map->objectApiNameVsLayoutNameList)’);

      System.debug(‘—>>>>Map(<String>, List<String>)      objectApiNameVsLayoutNameList’+objectApiNameVsLayoutNameList);

      set<String> abc = objectApiNameVsLayoutNameList.keyset();

      System.debug(‘—>>>Set abc=’+abc);

      String objectName  = ”;

      for(String s : abc) {

      objectname = s;

      }

     System.debug(‘—>>>objectname=’+objectname);       

     Map<String , List<SelectedObjectRecords1__c >> nameVsObject =Utility.apiNameVsListOfRecords(objectName      ); // SelectedObjectRecords1__c.getAll();

     System.debug(‘–>>>>Map nameVsObject=’+nameVsObject);

      map<String , String > objectApiNameVRelatedList = new map<String , String > ();

      MetadataService.MetadataPort service = createService();

      List<MetadataService.Metadata> layouyListToBeUpdated = new list<MetadataService.Metadata>();

      list<MetadataService.LayoutSection> layoutUser1 = new list<MetadataService.LayoutSection>();

      List<MetadataService.Layout> layoutList;

      for(String str : objectApiNameVsLayoutNameList.keyset()){

      layoutList =  (List<MetadataService.Layout>) service.readMetadata(‘Layout’,    objectApiNameVsLayoutNameList.get(str)).getRecords();

       }

       System.debug(‘—>>>>layoutList=’+layoutList);

       /////////////////////////This code is to remove the Section from page Layout – Start//////////////////////////////

       for(MetadataService.Layout lay : layoutList) {

       for(MetadataService.LayoutSection lSec : lay.layoutSections) {

       if(lSec.label == ‘Drag & Drop Section’) {

       System.debug(‘—>>>lSec.label=’+lSec.label);

       //lSec.remove();

       System.debug(‘–>>>lSec.layoutColumns’+lSec.layoutColumns);

       lSec.label = ‘ ‘;

       lSec.layoutColumns = new MetadataService.LayoutColumn[] {};

       System.debug(‘–>>>lSec.layoutColumns’+lSec.layoutColumns);

               }

           }

       }

       /////////////////////////This code is to remove the Section from page Layout – Start//////////////////////////////

     if(layoutList  != null ){  

      System.debug(‘—>>>Passing to handleSaveResults’);

       handleSaveResults(service.updateMetadata(layoutList)[0]);

       }

       } catch(Exception e){

          system.debug(‘—>>>>>Exception in deleteUpdatePageLayouts–>>>’ + e.getMessage() +                      e.getLineNumber());

      }

   }

For Deleting the Created Visualforce page:

Delete the Created Visualforce page

public static void deletePage(list<String> deletePages)

   {

       System.debug(‘—>>>In DeletePage—>>>deletePages=’+deletePages);

       String namespace12 = Utility.provideNamespace();

       for(String str : deletePages){

      System.debug(‘–>>>>1.)str=’+str);

      if(str.endsWith(‘__c’)){

       str = Utility.removeUnderscore(str);

      //  str = str.remove(namespace12);

      }

      System.debug(‘–>>>>2.)str=’+str);

       }

      MetadataService.MetadataPort service = createService();     

       List<MetadataService.DeleteResult> results =service.deleteMetadata(‘ApexPage’, deletePages);        

       handleDeleteResults(results[0]);

       System.debug(‘—>>>>Delete Results=’+results);

   }

For helper methods to be include in the same class in which you are using handleSaveResults, handleDeleteResults, handleUpsertResults:

handleSaveResults, handleDeleteResults, handleUpsertResults

public static void handleSaveResults(MetadataService.SaveResult saveResult) {

       // Nothing to see?

       if(saveResult==null || saveResult.success)

       return;

       // Construct error message and throw an exception

       if(saveResult.errors!=null) {

       List<String> messages = new List<String>();

       messages.add((saveResult.errors.size()==1 ? ‘Error ‘ : ”) +‘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, ‘ ‘));

       }

   if(!saveResult.success)

   throw new MetadataServiceExamplesException(‘Request failed with no specified error.’);

   }

/**

* Example helper method to interpret a SaveResult, throws an exception if errors are found

**/

public static void handleDeleteResults(MetadataService.DeleteResult deleteResult) {

       // Nothing to see?

     if(deleteResult==null || deleteResult.success)

      return;

       // Construct error message and throw an exception

     if(deleteResult.errors!=null) {

    List<String> messages = new List<String>();

    messages.add((deleteResult.errors.size()==1 ? ‘Error ‘ : ‘Errors ‘) + ‘occured processing component ‘ +   

   deleteResult.fullName + ‘.’);

  for(MetadataService.Error error : deleteResult.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, ‘ ‘));

       }

 if(!deleteResult.success)

 throw new MetadataServiceExamplesException(‘Request failed with no specified error.’);

   }

/**

* Example helper method to interpret a UpsertResult, throws an exception if errors are found

**/

public static void handleUpsertResults(MetadataService.UpsertResult upsertResult) {

       // Nothing to see?

 if(upsertResult==null || upsertResult.success)

 return;

       // Construct error message and throw an exception

 if(upsertResult.errors!=null) {

 List<String> messages = new List<String>();

 messages.add((upsertResult.errors.size()==1 ? ‘Error ‘ : ‘Errors ‘) +‘occured processing component ‘ + upsertResult.fullName + ‘.’);

for(MetadataService.Error error : upsertResult.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, ‘ ‘));

       }

 if(!upsertResult.success)

throw new MetadataServiceExamplesException(‘Request failed with no specified error.’);

   }

}


Author: AJ

Share This Post On

1 Comment

  1. heii
    i’m a salesforce developer please help me. I have already read your website all blogs its very use full and knowledgeable.
    i have a problem related to: “how to read current All ProfileFieldLevelSecurity” through metadat service class or any other way. please give me solution.

    Post a Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

ajay-certified-pic1

Interested In Knowing More...

Hi! I am Ajay Dubedi, Salesforce 5x Certified Along With JAVA Programmer Certification And JAVA Web Component Developer Certification. I am An Expert In Salesforce CRM Solutions With In-depth 7 Yrs Of Hands On Experience In Variety Of Salesforce Integrations, Customizations & App Development.

Let's Get In Touch & Start Working On Something Cool!

Hey! great, thank mate for sharing your email, I am pretty excited to know you visited my website & shown interest in my content. Just keep an eye on your inbox for my emails :)