Showing posts with label Apex Best Practices. Show all posts
Showing posts with label Apex Best Practices. Show all posts

Sunday, April 5, 2015

Get the Object Type by using sObject Describe call in Apex

public AccountControllerExtension(ApexPages.StandardController stdController){

// Get the record of sObject (e.g. Account, Contact etc.) by using the method "getRecord()" of StandardController
    sObject sObjectRecord = stdController.getRecord();

// Get the object type specifically by using Apex sObject Describe call
// In this case it will be Account
    String objectType = sObjectRecord.getSObjectType().getDescribe().getName();  

// Verify the Object Type
System.Debug('>>Object Type<<'+objectType);

}

Get the Picklist Values by using sObject Describe call in Apex

// Contains all Account.Industry values
Set<String> IndustryValues = new Set<String>();

// Get Account.Industry values from the field on Account object
Schema.DescribeFieldResult accountIndustry = Account.Industry.getDescribe();

List<Schema.PicklistEntry> accountIndustryValues = accountIndustry.getPicklistValues();        
for(Schema.PicklistEntry industryValue: accountIndustryValues){
IndustryValues.add(industryValue.getValue());
}

System.Debug('>>Account Industry Values<<'+IndustryValues);

Result should be as follows

>>Account Industry Values<<{Agriculture, Apparel, Banking, Biotechnology, Chemicals, Communications, Construction, Consulting, Education, Electronics, ...}

Convert Complex String into Normal Format in Apex

// An array contains lst of Strings 
// Name, Title/Role, Company Name 
List<String> lstIntroductionWords = new List<String>{'Marc Benioff', 'CEO', 'Salesfore.com'};

// A string contains senetence template for the introduction
String templateIntroduction = 'My name is {0}. I am The {1} of {2}.';    

// A string contains sentence with complete words populated in a template sentence
String completeIntroduction = String.format(templateIntroduction, lstIntroductionWords);    

// See the complete sentence for the introduction
System.Debug('>>Introduction<<'+completeIntroduction);

Result should be as below sentence
>>Introduction<< My name is Marc Benioff. I am The CEO of Salesfore.com.

Convert String into Acceptable DateTime in Apex

// API Response DateTime = 2015-03-16T16:04:56.0000000+00:00
// Acceptable Format = 2015-03-16 16:04:56

// DateTime in String format
String dateTimeInString = '2015-03-16T16:04:56.0000000+00:00';

// Convert String into DateTime using "replace" method of String and "Valueof" method of DateTime
DateTime acceptableDateTime = DateTime.Valueof(dateTimeInString.replace('T', ' ')); 

System.Debug('>>Acceptable DateTime :<<'+acceptableDateTime);

Result

>>Acceptable DateTime :<< 2015-03-16 16:04:56