Apex Code Snippets

Last Updated on April 19, 2023 by Sudhir

GET COUNT OF RECORDS BY A PARTICULAR ATTRIBUTE/FIELD

[SELECT Status, COUNT(id) numRecs FROM Case GROUP BY Status];

GET FIELD NAMES OF AN OBJECT

// replace Case with the appropriate object
Schema.DescribeSObjectResult dsr = Case.sObjectType.getDescribe();
Map<String, Schema.SObjectField> fieldMap = dsr.fields.getMap();
for (String fieldName : fieldMap.keySet())
{
  System.debug('%' + dsr.getName() + '% Label: %' + 
  fieldMap.get(fieldName).getDescribe().getLabel() + '% Field Name: %' + fieldName);
}

GET A LIST OF ALL OBJECTS

List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();  
for(Schema.SObjectType f : gd)
{
   System.debug(f.getDescribe().getLabel());
}

GET A LIST OF ALL OUTBOUND CHANGE SETS

PageReference pr=new PageReference('/changemgmt/listOutboundChangeSet.apexp');
Blob output=pr.getContent();
System.debug('### Content = \n' + output.toString());

GET IP ADDRESS

// Get the IP address for the user submitting the webform. 

 public static String GetUserIPAddress() {
   string ReturnValue = ''; 
   // True-Client-IP has the value when the request is coming via the caching integration.
   ReturnValue = ApexPages.currentPage().getHeaders().get('True-Client-IP');
   // X-Salesforce-SIP has the value when no caching integration or via secure URL.
   if (ReturnValue == '' || ReturnValue == null) {
     ReturnValue = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
   } // get IP address when no caching (sandbox, dev, secure urls)
  
   if (ReturnValue == '' || ReturnValue == null) {
     ReturnValue = ApexPages.currentPage().getHeaders().get('X-Forwarded-For');
   } // get IP address from standard header if proxy in use

   return ReturnValue;
 } // GetUserIPAddress

GET DATA FROM CUSTOM METADATA TYPES

String queueExt = '69381';

CTI_Case_Queue__mdt[] queueMapping = [SELECT MasterLabel, Label, DeveloperName, Queue_Extension__c, Queue_Name__c 
                  FROM CTI_Case_Queue__mdt
                  WHERE Queue_Extension__c = :queueExt];

System.debug('==== queueExt: ' + queueExt);
System.debug('==== num of records: ' + queueMapping.size());

for(CTI_Case_Queue__mdt q : queueMapping)
{
 System.debug('==== MasterLabel: ' + q.MasterLabel);
 System.debug('==== Label: ' + q.Label);
 System.debug('==== DeveloperName: ' + q.DeveloperName);
 System.debug('==== Queue_Extension__c: ' + q.Queue_Extension__c);
 System.debug('==== Queue_Name__c: ' + q.Queue_Name__c);
}

PUBLISH A DOCUMENT INTO A LIBRARY

if(!documentIdsList.isEmpty()){ // add the document to the unpublished library first.
        Id internalLibraryId = FDICUtil.getLibraryId('EDOS Community - Unpublished Files');
        ContentWorkspace internalLib = [Select Id FROM ContentWorkspace WHERE NAME = 'EDOS Community - Unpublished Files'];
        if (internalLibraryId != null) {
// link the file to the unpublished library by default. When the order gets published the file will be
// shared with t he published library. We can remove the share with the public library but we can't remove it from
// the unpublished library since that was the first library the file was shared with. By default the first library
// the document gets linked to is the owner of that library, so link it to the unpublished library first.

          for(Id docId: documentIdsList) {
            //ContentWorkspaceDoc cwd = new ContentWorkspaceDoc(ContentDocumentId = docId, ContentWorkspaceId = internalLibraryId);             
            ContentWorkspaceDoc cwd = new ContentWorkspaceDoc(ContentDocumentId = docId, ContentWorkspaceId = internalLib.Id);  
            addToLibraryList.add(cwd);
          }
        }

        if(!addToLibraryList.isEmpty()) {
          insert addToLibraryList;
        }
      }

GET A LIST OF ALL RELATED OBJECTS FROM A PARENT OBJECT

Set<String> results = new Set<String>();
for( ChildRelationship r: Case.SObjectType.getDescribe().getChildRelationships()) {
  results.add(string.valueOf(r.getChildSObject()));
}
system.debug(string.join(new List<String>(results), ', '));

GET FIELDS ON PAGE LAYOUT USING APEX METADATA API:

//list to hold all account layouts.
List<Metadata.Metadata> accountLayout = Metadata.Operations.retrieve(Metadata.MetadataType.Layout, new List<String> {'Account-Account Layout'});

//map to hold each section and a list of their fields.
Map<String, List<String>> layoutFieldsMap = new Map<String, List<String>>();

System.debug('accountLayouts: ' + accountLayout);

//get the first layout information
if(!accountLayout.isEmpty()) {
    Metadata.Layout layoutMd = (Metadata.Layout) accountLayout.get(0);
    
    //loop through each section and get fields in each column
    for (Metadata.LayoutSection section : layoutMd.layoutSections) {
        System.debug('Section: ' + section.label);
        List<String> fields = new List<String>();
        
        //go through each column and get the fields.
        for (Metadata.LayoutColumn column : section.layoutColumns) {     
            if (column.layoutItems != null) {
                for (Metadata.LayoutItem item : column.layoutItems) {
                    System.debug('Field: ' + item.field);
                    fields.add(item.field);
                }
            }
            //store fields list in a map with the section name as key
            layoutFieldsMap.put(section.label, fields);
        }
    }
    
    System.debug('fields map: ' + layoutFieldsMap); //fields is getting nulled out. figure it out.
    for(String key : layoutFieldsMap.keySet()){
        List<String> f = layoutFieldsMap.get(key);
        System.debug('key: ' + key);
        System.debug('f: ' + f);
    }
}
else {
    System.debug('Did not find the layout specified');
}

GET LIMITS FOR THE ORG

//Get list of what limits are available.
List<System.OrgLimit> limits = OrgLimits.getAll();
for (System.OrgLimit aLimit: limits) {
  System.debug('Limit Name ' + aLimit.getName());
}

Map<String,System.OrgLimit> limitsMap = OrgLimits.getMap();
System.OrgLimit dataStorageLimit = limitsMap.get('DataStorageMB');
System.OrgLimit fileStorageLimit = limitsMap.get('FileStorageMB');

// Max and usage limit values of dataStorageLimit
System.debug('dataStorageLimit Value: ' + dataStorageLimit.getValue());
System.debug('Maximum Limit: ' + dataStorageLimit.getLimit());

// Max and usage limit values of fileStorageLimit
System.debug('fileStorageLimit Value: ' + fileStorageLimit.getValue());
System.debug('Maximum Limit: ' + fileStorageLimit.getLimit());

GET NUMBER OF USERS ASSIGNED TO EACH PERMISSION SET

SELECT PermissionSet.Name, Count(Id) From PermissionSetAssignment
WHERE Assignee.isActive = true
AND PermissionSet.IsOwnedByProfile = false
Group By PermissionSet.Name
Order By Count(Id) DESC

GET NUMBER OF USERS ASSIGNED TO EACH PROFILE

SELECT count(Id), Profile.Name FROM User GROUP BY Profile.Name /* NOTE: make sure to filter by active users if you want only active users */

Export Object Level Permissions for All Profiles and Permission Sets – Data Loader

SELECT Parent.Profile.Name, Parent.Label, Parent.IsOwnedByProfile, SobjectType, PermissionsRead, PermissionsCreate, PermissionsEdit, PermissionsDelete, PermissionsViewAllRecords, PermissionsModifyAllRecords FROM ObjectPermissions ORDER BY Parent.Profile.Name, Parent.Label, SobjectType

Export Field Level Security for All Profiles and Permission Sets – Data Loader

SELECT Parent.Profile.Name, Parent.Label, Parent.IsOwnedByProfile, SobjectType, Field, PermissionsEdit, PermissionsRead FROM FieldPermissions ORDER BY Parent.Profile.Name, Parent.Label, SobjectType, Field

GET LIST OF APPS

SELECT Id, ApplicationId, Name, Label, Type FROM AppMenuItem Where type='TabSet' /* NOTE: remove where clause to see all application types (Network, Connected Apps, etc.). TabSet is for Salesforce Apps created for users */

GET LIST OF PROFILES WITH ACCESS TO APPS

SELECT Id, SetupEntityId, ParentId, Parent.Label, Parent.IsCustom, Parent.IsOwnedByProfile, Parent.ProfileId, Parent.Profile.Name FROM SetupEntityAccess WHERE SetupEntityType = 'TabSet' AND Parent.IsOwnedByProfile = true ORDER BY Parent.ProfileId

Author: Sudhir

I am a Salesforce Certified Application Architect. My passion is to enable my clients to realize their goal of deploying enterprise-wide Salesforce solutions to alleviate their pain points and help them realize efficiencies, be it of scale or in day-to-day tasks.