Sunday, August 13, 2017

Using Dynamic Apex to retrieve Picklist Values

USECASE: Fetch the picklist values from Industry field of Account sObject.

List<SelectOption> options = new List<SelectOption>();

Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();
List<Schema.PicklistEntry> picklistEntries = fieldResult.getPicklistValues();

for (Schema.PicklistEntry picklistEntry : picklistEntries) {
    options.add(new SelectOption(picklistEntry.getLabel(), picklistEntry.getValue()));
}

return options;

OR

List<SelectOption> options = new List<SelectOption>();

Map<String, Schema.SObjectField> fieldMap = Account.getSObjectType().getDescribe().fields.getMap();
List<Schema.PicklistEntry> picklistEntries = fieldMap.get('Industry').getDescribe().getPickListValues();

for (Schema.PicklistEntry picklistEntry : picklistEntries) {
    options.add(new SelectOption(picklistEntry.getLabel(), picklistEntry.getValue()));
}

return options;

Share This:    Facebook Twitter

DescribeSObjectResult: Check whether the object is Custom or Standard


List<String> allCustomObjsList = new List<string>();
List<String> allStandardObjsList = new List<string>();

for(Schema.SobjectType obj : Schema.getGlobalDescribe().values()) {
    Schema.DescribeSobjectResult objResult = obj.getDescribe();
    if(objResult.isCustom()) {
        String strObjName =objResult.getname();
        allCustomObjsList.add(strObjName);
    }
    else {
        String strObjName =objResult.getname();
        allStandardObjsList.add(strObjName);
    }
}

System.debug('Custom Objects List: ' +allCustomObjsList);
System.debug('Standard Objects List: ' +allStandardObjsList);

If you need to check for a specific object, execute the below code:
Schema.DescribeSObjectResult describeAccount = Schema.sObjectType.Account;
System.debug(describeAccount.isCustom());

Similarly you can use other methods for describing sObjects, the list of which can be found below:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject_describe.htm

Share This:    Facebook Twitter

Fetch recordType Name and recordTypeId without SOQL

To avoid SOQL Limit we can use dynamic apex to get RecordTypeId. We can get a particular RecordTypeId of a particular sObject or get all recordTypeid of one sobejct in a map.

global class RecordTypeUtils {
    
    //Method to get the recordTypeId 
    public static Id recordTypeId(string obj,string recName){
        Id recTypeId;
        if(obj!= null && recName != null){
            recTypeId= Schema.getGlobalDescribe().get(obj).getDescribe().getRecordTypeInfosByName().get(recName).getRecordTypeId();
        }  
        return recTypeId;  
    }
    
    //Method to get the map of recordType Name as key and recordTypeId as value 
    public static Map<String,Id> recordTypeMap(string obj){
        Map<String,Id> recTypeNameWithIdMap=new Map<String,Id>();
        if(obj!= null){
            for(Schema.RecordTypeInfo recInfo : Schema.getGlobalDescribe().get(obj).getDescribe().getRecordTypeInfosByName().values()){
                recTypeNameWithIdMap.put(recInfo.getName(),recInfo.getRecordTypeId());
            }
        }
        return recTypeNameWithIdMap;
    } 
}

I created a record type "NewLabel" on Account object. Enter the below Apex code in Execute Anonymous window and check the output:

Map<String,Id> recTypeIdMap=RecordTypeUtils.recordTypeMap('Account');
System.debug(recTypeIdMap);
Id recId=RecordTypeUtils.recordTypeId('Account','NewLabel');
System.debug(recId);

Id recordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('NewLabel').getRecordTypeId(); 
System.debug(recordTypeId);

Note that values of recId and recordTypeId in your output is same.

Check the link below to check a utility class that performs the query against the RecordType object
https://interactiveties.com/blog/2016/recordtype-utility-class.php
Share This:    Facebook Twitter

Saturday, August 12, 2017

Apex: Get sObject details using ID

Id id = 'a0M7F000000qXgg';
Schema.sObjectType objType = id.getSObjectType();
Schema.DescribeSObjectResult objDescribe = objType.getDescribe();

System.debug(objDescribe.getName());

Similarly, you can get other sObject details using the methods described in the link below:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject_describe.htm
Share This:    Facebook Twitter

Dynamic SOQL and SOSL

To create a dynamic SOQL query at run time, use the database query method. Check the reference link for more details.
List<sObject> sobjList = Database.query(string);

To create a dynamic SOSL query at run time, use the search query method. For example:
String searchquery = 'FIND \'Edge*\' IN ALL FIELDS RETURNING Account(Id, Name), Contact, Lead';
List<List<SObject>>searchList = search.query(searchquery);

To prevent SOSL injection, use the escapeSingleQuotes method. This method adds the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands.
fieldList = (fieldList!=null) ? String.escapeSingleQuotes(fieldList) : fieldList;

References:
http://metillium.com/2016/03/variable-binding-in-dynamic-soql/
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top