Sunday, August 19, 2012
Well today while trying to retrieve the label of a field dynamically I found a hidden capability of visualforce!
It not only can retrieve the "label" but almost everything that can be retrieved using "DescribeSObjectResult" and "DescribeFieldResult" .
Instead of rushing into the topic proceed step by step.
Example : Dynamically retrieving the label of Account say phone.
<apex:outputLabel value="{!$ObjectType.Account.fields.Phone.label}"/>
Well we can also retrieve the API name of the field by just changing the "label" with "name"
<apex:outputLabel value="{!$ObjectType.Account.fields.Phone.name}"/>
Well thats not all you can also get the datatype of the field
<apex:outputLabel value="{!$ObjectType.Account.fields.Phone.type}"/>
So what we are actually doing here?
Well if we simply write "$ObjectType.Account.fields.Phone" we are actually describing the phone field which is equivalent to "Schema.DescribeFieldResult" now if you see the salesforce doumentation for "Schema.DescribeFieldResult"(http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_fields_describe.htm). Now if you see the above page there are lots of methods defined like say "getLength()" you can simple access the value by dropping the "get" and writing :
<apex:outputLabel value="{!$ObjectType.Account.fields.Phone.length}"/>
How to do this dynamically?
<apex:outputLabel value="{!$ObjectType.Account.fields[fieldName].label}"/>
Where "fieldName" is the fieldApi Name.
What else we can do?
Well if you check this page (http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_describesobjects_describesobjectresult.htm) you can almost call every method described in this page. Doing "$ObjectType.Account" actually describes the Account object and now after describing the object you can call almost any of the above methods described in salesforce documentation for "DescribeSObjectResult".
Example 1: Say if I want to retrieve the plural label for sObject "Account" my VF code will be
<apex:outputLabel value="{!$ObjectType.Account.labelPlural}"/>
Example 2 : If I want retrieve the "keyPrefix"
<apex:outputLabel value="{!$ObjectType.Account.keyPrefix}"/>
Like this we can almost get all the properties for a object describe
One with the keyPrefix something quite useful. Can skip writing those 2 liner GetKeyPrefix methods in controller. Thanks for sharing!!
ReplyDeleteNot only keyPrefix it can do lot more! Its just not documented!
Delete