Menu Bar

Monday 5 November 2012

Understanding Global Variables

Understanding Global Variables

S-controls and formulas available in: Contact Manager, Group, Professional, Enterprise, Unlimited, and Developer Editions
Custom buttons and links are available in: All Editions
Visualforce available in: Contact Manager, Group, Professional, Enterprise, Unlimited, and Developer Editions
$Profile global merge field type available in: Enterprise, Unlimited, and Developer Editions

User Permissions Needed
To create, edit, and delete custom s-controls, formulas, or Visualforce pages:“Customize Application”
Components such as s-controls, custom buttons, custom links, formulas, and Visualforce pages allow you to use special merge fields to reference the data in your organization. Use the following global variables when choosing a merge field type to add to your custom component:

$Action

Description:A global merge field type to use when referencing standard Salesforce actions such as displaying the Accounts tab home page, creating new accounts, editing accounts, and deleting accounts. Use action merge fields in LINKTO and URLFOR functions to reference the action selected.
Use:
  1. Select the field type: $Action.
  2. Insert a merge field in the format $Action.object.action, such as $Action.Account.New.
    Note
    For a list of actions and their supported objects, see Valid Values for the $Action Global Variable.
S-Control Example:The s-control below references the standard action for creating new accounts in the $Action.Account.New merge field.
<html>
<body>
{!LINKTO("Create a New Account", ​$Action.Account.New​, 
  $ObjectType.Account)}
</body>
</html>
VisualforceExample:
<apex:outputLink value="{!URLFOR($Action.Account.New)}">Create New Account</apex:outputLink>
Tips:This global variable is only available for custom buttons and links, s-controls, and Visualforce pages.

$Api

Description:A global merge field type to use when referencing API URLs.
Use:
  1. Select the field type: $Api.
  2. Select a merge field, such as:
    • $Api.Enterprise_Server_URL__xxx: The Enterprise WSDL SOAP endpoint where xxx represents the version of the API. For example, $Api.Enterprise_Server_URL_140 is the merge field value for version 14.0 of the API.
    • $Api.Partner_Server_URL__xxx: The Partner WSDL SOAP endpoint where xxx represents the version of the API. $Api.Partner_Server_URL_120 is the merge field value for version 12.0 of the API.
    • $Api.Session_ID: The session ID.
S-Control Example:The custom formula field below calls a service to replace the SIC code. Replace myserver with the name of your server.
HYPERLINK("https://www.myserver.com/mypage.jsp" & 
"?Username="       & $User.Username & 
"&crmSessionId="   & GETSESSIONID() & 
"&crmServerUrl="   &  $Api.Partner_Server_URL_90  &
"&crmObjectId="    & Id &
"&crmFieldUpdate=sicCode",
"Update SIC Code")
VisualforceExample:Use dot notation to return the session ID.
{!$Api.Session_ID}
Tips:This global variable is only available for formula fields, s-controls, custom buttons and links, and Visualforce pages.

$Component

Description:A global merge field type to use when referencing a Visualforce component.
Use:Each component in a Visualforce page has its own id attribute. When the page is rendered, this attribute is the same as the Document Object Model (DOM) ID.Use $Component.Id in JavaScript to reference a specific component on a page.
VisualforceExample:
function beforeTextSave() {
   document.getElementById('{!$component.msgpost}').value = myEditor.getEditorHTML();
}
Tips:This global variable is only available for Visualforce pages.

$componentLabel

Description:A global merge field to use when referencing the label of an inputField component on a Visualforce page that is associated with a message.
Use:Return the label of an inputField component that is associated with a message.
Visualforce Example:
<apex:datalist var="mess" value="{!messages}">
  <apex:outputText value="{!mess.componentLabel}:" style="color:red/>
  <apex:outputText value="{!mess.detail}" style="color:black" />
</apex:datalist>
Tips:This global variable is only available for Visualforce pages.

$CurrentPage

Description:A global merge field type to use when referencing the current Visualforce page.
Use:Use this expression in a Visualforce page to access the current page parameters and values, the current page name ($CurrentPage.Name), or the URL of the current page ($CurrentPage.URL).
Visualforce Example:
<apex:page standardController="Account">
    <apex:pageBlock title="Hello {!$User.FirstName}!">
        You belong to the {!account.name} account.<br/>
        You're also a nice person.
    </apex:pageBlock>
    <apex:detail subject="{!account}" relatedList="false"/>
    <apex:relatedList list="OpenActivities" 
      subject="{!$CurrentPage.parameters.relatedId}"/> 
</apex:page>
Tips:This global variable is only available for Visualforce pages.

$Label

Description:A global merge field type to use when referencing a custom label in a Visualforce page.
Use:Use this expression in a Visualforce page to access a custom label. When the application server constructs the page to be presented to the end-user’s browser, the value returned depends upon the language setting of the contextual user. The value returned is one of the following, in order of precedence:
  1. the local translation's text
  2. the packaged translation's text
  3. the master label's text
VisualforceExample:
<apex:page>
   <apex:pageMessage severity="info" 
   strength="1" 
   summary="{!$Label.firstrun_helptext}" 
   />
</apex:page>
Tips:This global variable is only available for Visualforce pages.

$Label.Site

Description:A global merge field type to use when referencing a standard label in a Visualforce page. Like all standard labels, the text will display based on the user's language and locale.
Use:Use this expression in a Visualforce page to access a standard label. When the application server constructs the page to be presented to the end-user’s browser, the value returned depends on the language and locale of the user.
Salesforce provides the following labels:
LabelMessage
authorization_requiredAuthorization Required
bandwidth_limit_exceededBandwidth Limit Exceeded
change_passwordChange Password
change_your_passwordChange Your Password
click_forget_passwordIf you have forgotten your password, click Forgot Password to reset it.
community_nicknameNickname
confirm_passwordConfirm Password
down_for_maintenance<i>{0}</i> is down for maintenance
emailEmail
email_usemail us
enter_passwordDid you forget your password? Please enter your username below.
errorError: {0}
error2Error
file_not_foundFile Not Found
forgot_passwordForgot Password
forgot_password_confirmationForgot Password Confirmation
forgot_your_password_qForgot Your Password?
get_in_touchPlease <a href="{0}">{1}</a> if you need to get in touch.
go_to_login_pageGo to Login Page
img_path/img/sites
in_maintenanceDown For Maintenance
limit_exceededLimit Exceeded
loginLogin
login_buttonLogin
login_or_register_firstYou must first log in or register before accessing this page.
logoutLogout
new_passwordNew Password
new_user_qNew User?
old_passwordOld Password
page_not_foundPage Not Found
page_not_found_detailPage Not Found: {0}
passwordPassword
passwords_dont_matchPasswords did not match.
powered_byPowered by
registerRegister
registration_confirmationRegistration Confirmation
site_loginSite Login
site_under_constructionSite Under Construction
sorry_for_inconvenienceSorry for the inconvenience.
sorry_for_inconvenience_back_shortlySorry for the inconvenience. We'll be back shortly.
stay_tunedStay tuned.
submitSubmit
temp_password_sentAn email has been sent to you with your temporary password.
thank_you_for_registeringThank you for registering. An email has been sent to you with your temporary password.
under_construction<i>{0}</i> is under construction
user_registrationNew User Registration
usernameUsername
verify_new_passwordVerify New Password
Visualforce Example:
<apex:page>
   <apex:pageMessage severity="info" 
   strength="1" 
   summary="{!$Label.Site.temp_password_sent}" 
   />
</apex:page>
Tips:This global variable is only available for Visualforce pages.

$ObjectType

Description:A global merge field type to use when referencing standard or custom objects such as accounts, cases, or opportunities as well as the value of a field on that object. Use object type merge fields in LINKTO,GETRECORDIDS, and URLFOR functions to reference a specific type of data or the VLOOKUP function to reference a specific field in a related object.
Use:
  1. Select the field type: $ObjectType.
  2. Select an object to insert a merge field representing that object, such as $ObjectType.Case.
    Optionally, select a field on that object using the following syntax: $ObjectType.Role_Limit__c.Fields.Limit__c.
Custom Button Example:The custom list button below references the cases standard object in the$ObjectType.Case merge field.
{!REQUIRESCRIPT
("/soap/ajax/13.0/connection.js")} 

var records = {!GETRECORDIDS($ObjectType.Sample)}; 
var newRecords = []; 

if (records[0] == null) 
{ 
alert("Please select at least one row") 
} 
else 
{ 
for (var n=0; n<records.length; n++) { 
var c = new sforce.SObject("Case"); 
c.id = records[n]; 
c.Status = "New"; 
newRecords.push(c); 
} 

result = sforce.connection.update(newRecords); 

window.location.reload(); 
}
Validation Rule Example:This example checks that a billing postal code is valid by looking up the first five characters of the value in a custom object called Zip_Code__c that contains a record for every valid zip code in the US. If the zip code is not found in the Zip_Code__c object or the billing state does not match the corresponding State_Code__c in the Zip_Code__c object, an error is displayed.
AND(
LEN(BillingPostalCode) > 0,
OR(BillingCountry = "USA", 
   BillingCountry = "US"),
VLOOKUP(
$ObjectType.Zip_Code__c.Fields.State_Code__c,
$ObjectType.Zip_Code__c.Fields.Name,
LEFT(BillingPostalCode,5)) 

<> BillingState
)
VisualforceExample:The following example retrieves the label for the account namefield:
{!$ObjectType.account.fields.name.label}
Tips:This global variable is available in Visualforce pages, custom buttons and links, s-controls and validation rules.

$Organization

Description:A global merge field type to use when referencing information about your company profile. Use organization merge fields to reference your organization's city, fax, ID, or other details.
Use:
  1. Select the field type: $Organization.
  2. Select a merge field such as $Organization.Fax.
Validation Rule Example:Use organization merge fields to compare any attribute for your organization with that of your accounts. For example, you may want to determine if your organization has the same country as your accounts. The validation formula below references your organization's country merge field and requires a country code for any account that is foreign.
AND($Organization.Country <> BillingCountry, ISNULL( Country_Code__c ) )
VisualforceExample:Use dot notation to access your organization's information. For example, to retrieve the street and state of your organization, use the following:
{!$Organization.Street}
{!$Organization.State}
Note that you cannot use the {!$Organization.UiSkin} in Visualforce.
Tips:The organization merge fields get their values from whatever values are currently stored as part of your company information in Salesforce.

$Page

Description:A global merge field type to use when referencing a Visualforce page.
Use:Use this expression in a Visualforce page to access another Visualforce page.
Visualforce Example:
<apex:page>
  <h1>Linked</h1>
  <a href="{!$Page.otherPage}">This is a link to another page</a>
</apex:page>
Tips:This global variable is only available for Visualforce pages.

$Profile

Description:A global merge field type to use when referencing information about the current user's profile. Use profile merge fields to reference information about the user's profile such as license type or name.
Use:
  1. Select the field type: $Profile.
  2. Select a merge field such as $Profile.Name.
Validation Rule Example:The validation rule formula below references the profile name of the current user to ensure that only the record owner or users with this profile can make changes to a custom field called Personal Goal:
AND(
   ISCHANGED( Personal_Goal__c ),
   Owner <> $User.Id,
    $Profile.Name <> "Custom: System Admin"
)
Visualforce Example:To return the current user's profile, use the following:
{$Profile.Name}
Tips:
  • $Profile merge fields are only available in Editions that can create custom profiles.
  •  Use profile names to reference standard profiles in $Profile merge fields. If you previously referenced the internal value for a profile, use the following list to determine the name to use instead:
    Standard Profile Name$Profile Value
    System AdministratorPT1
    Standard UserPT2
    Ready OnlyPT3
    Solution ManagerPT4
    Marketing UserPT5
    Contract ManagerPT6
    Partner UserPT7
    Standard Platform UserPT8
    Standard Platform One App UserPT9
    Customer Portal UserPT13
    Customer Portal ManagerPT14
  • Your merge field values will be blank if the profile attributes are blank. For example profile Description is not required and may not contain a value.
  • You do not need to give users permissions or access rights to their profile information to use these merge fields.

$RecordType

Description:A global merge field to use when referencing a record type.
Use:Add $RecordType manually to your s-control.
VisualforceExample:To return the ID of the current record type, use the following:
{$RecordType.Id}
Tips:
  • Use $RecordType.Id to reference a specific record type instead of $RecordType.Id. While $RecordType.Id makes a formula more readable, you must update the formula if the name of the record type changes, whereas the ID of a record type never changes.
  • Do not reference any field with the $RecordType variable in cross-object formulas. The $RecordType variable only resolves to the record containing the formula, not the record to which the formula spans.

$Request

Description:A global merge field to use when referencing a query parameter by name that returns a value.
Use:Add $Request manually to your s-control.
S-Control Example:The snippet below, named Title_Snippet, requires two input parameters: titleTheme and titleText. You can reuse it in many s-controls to provide page title and theme in your HTML.
<h2 class=”{!$Request.titleTheme}.title”>​{!$Request.titleText}</h2>
The s-control below calls this snippet using the INCLUDE function, sending it the parameters for both the title and theme of the HTML page it creates.
<html>
<head>
</head>
<body>
{! INCLUDE($SControl.Title_Snippet, 
[titleTheme = "modern", titleText = "My Sample Title"]) }

... Insert your page specific content here ...

</body>
</html>
Tips:Do not use $Request in Visualforce pages to reference query parameters. Use $CurrentPage instead.

$Resource

Description:A global merge field type to use when referencing an existing static resource by name in a Visualforce page. You can also use resource merge fields in URLFOR functions to reference a particular file in a static resource archive.
Use:Use $Resource to reference an existing static resource. The format is $Resource.nameOfResource, such as $Resource.TestImage.
VisualforceExamples:The Visualforce component below references an image file that was uploaded as a static resource and given the name TestImage:
<apex:image url="{!$Resource.TestImage}" width="50" height="50"/>
To reference a file in an archive (such as a .zip or .jar file), use the URLFOR function. Specify the static resource name that you provided when you uploaded the archive with the first parameter, and the path to the desired file within the archive with the second. For example:
<apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}" 
    width="50" height="50"/>
Tips:This global variable is only available for Visualforce pages.

$SControl

Important
S-controls have been superseded by Visualforce pages. After March 2010 organizations that have never created s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls will remain unaffected, and can still be edited.
Description:A global merge field type to use when referencing an existing custom s-control by name. Use s-control merge fields in LINKTO, INCLUDE, and URLFOR functions to reference one of your custom s-controls.
Use:
  1. Select the field type: $SControl.
  2. Select an s-control to insert a merge field representing that s-control, such as $Scontrol.Header_Snippet.
S-Control Example:The s-control below references the snippet in the $Scontrol.Header_Snippet merge field:
<html>
<body>
{! INCLUDE($SControl.Header_Snippet, 
[title = "My Title", theme = "modern"])}
</body>
</html>
VisualforceExample:The following example shows how to link to an s-control named HelloWorld in a Visualforce page:
<apex:page>
<apex:outputLink value="{!$SControl.HelloWorld}">Open the HelloWorld s-control</apex:outputLink>
</apex:page>
Note that if you simply want to embed an s-control in a page, you can use the <apex:scontrol> tag without the $SControl merge field. For example:
<apex:page>
<apex:scontrol controlName="HelloWorld" />
</apex:page>
Tips:
  • The drop-down list for Insert Merge Field lists all your custom s-controls except snippets. Although snippets are s-controls, they behave differently. For example, you cannot reference a snippet from aURLFOR function directly; snippets are not available when creating a custom button or link that has a Content Source of Custom S-Control; and you cannot add snippets to your page layouts. To insert a snippet in your s-control, use the Insert Snippet drop-down button.
  • This global variable is only available for custom buttons and links, s-controls, and Visualforce pages.

$Site

Description:A global merge field type to use when referencing information about the current Force.com site.
Use:
Use dot notation to access information about the current Force.com site. Note that only the following site fields are available:
Merge FieldDescription
{!$Site.Name}Returns the API name of the current site.
{!$Site.Domain}Returns the Force.com domain name for your organization.
{!$Site.CustomWebAddress}Returns the value of the Custom Web Address field for the current site.
{!$Site.OriginalUrl}Returns the original URL for this page if it is a designated error page for the site; otherwise, returns null.
{!$Site.CurrentSiteUrl}Returns the value of the site URL for the current request (for example, http://myco.com/ orhttps://myco.force.com/prefix/).
{!$Site.LoginEnabled}Returns true if the current site is associated with an active login-enabled portal; otherwise returns false.
{!$Site.RegistrationEnabled}Returns true if the current site is associated with an active self-regitration-enabled Customer Portal; otherwise returns false.
{!$Site.IsPasswordExpired}For authenticated users, returns true if the currently logged-in user's password is expired. For non-authenticated users, returns false.
{!$Site.AdminEmailAddress}Returns the value of the Site Contact field for the current site.
{!$Site.Prefix}Returns the URL path prefix of the current site. For example, if your site URL ismyco.force.com/partners, partners is the path prefix. Returns null if the prefix is not defined, or if the page was accessed using a custom Web address.
{!$Site.Template}Returns the template name associated with the current site; returns the default template if no template has been designated.
{!$Site.ErrorMessage}Returns an error message for the current page if it is a designated error page for the site and an error exists; otherwise, returns an empty string.
{!$Site.ErrorDescription}Returns the error description for the current page if it is a designated error page for the site and an error exists; otherwise, returns an empty string.
{!$Site.AnalyticsTrackingCode}The tracking code associated with your site. This code can be used by services like Google Analytics to track page request data for your site.
Visualforce Example:The following example shows how to use the $Site.Template merge field:
<apex:page title="Job Application Confirmation" showHeader="false" 
    standardStylesheets="true">
<!-- The site template provides layout & style for the site -->
  <apex:composition template="{!$Site.Template}">
  <apex:define name="body">
    <apex:form>
      <apex:commandLink value="<- Back to Job Search" 
          onclick="window.top.location='{!$Page.PublicJobs}';return false;"/>
      <br/>
      <br/>
      <center><apex:outputText value="Your application has been saved. Thank 
          you for your interest!"/></center>
      <br/>
      <br/>
    </apex:form>
  </apex:define>
  </apex:composition>
</apex:page>
Tips:This global variable is available in Visualforce pages, email templates, and s-controls.

$System.OriginDateTime

Description:A global merge field that represents the literal value of 1900-01-01 00:00:00. Use this global variable when performing date/time offset calculations or to assign a literal value to a date/time field.
Use:
  1. Select the field type: $System.
  2. Select OriginDateTime from the Insert Merge Field option.
Formula Example:The example below illustrates how to convert a date field into a date/time field. It uses the date in the OriginDateTime merge field to get the number of days since a custom field called My Date Field. Then, it adds the number of days to the OriginDateTime value.
$System.OriginDatetime + ( My_Date_Field__c - DATEVALUE($System.OriginDatetime) )
Note
OriginDateTime is in the GMT time zone but the result is displayed in the user's local time zone.
VisualforceExample:The following example calculates the number of days that have passed since 1900:
{!NOW() - $System.OriginDateTime}
Tips:This global variable is available in Visualforce pages, default values, field updates, formula fields, s-controls, and validation rules.

$User

Description:A global merge field type to use when referencing information about the current user. User merge fields can reference information about the user such as alias, title, and ID.
Use:
  1. Select the field type: $User.
  2. Select a merge field such as $User.Username.
Validation Rule Example:The validation rule formula below references the ID of the current user to determine if the current user is the owner of the record. Use an example like this to ensure that only the record owner or users with an administrator profile can make changes to a custom field called Personal Goal:
AND(
   ISCHANGED( Personal_Goal__c ),
   Owner <> $User.Id,
    $Profile.Name <> "Custom: System Admin"
)
VisualforceExample:The following example displays the current user's company name, as well as the status of the current user (which returns a Boolean value).
<apex:page>
  <h1>Congratulations</h1>
   This is your new Apex Page
   <p>The current company name for this 
      user is: {!$User.CompanyName}</p>
   <p>Is the user active?  
      {!$User.isActive}</p>
</apex:page>
Tips:
  • The current user is the person changing the record that prompted the default value, validation rule, or other operation that uses these global merge fields.
  • When a Web-to-Case or Web-to-Lead process changed a record, the current user is the Default Lead Owner or Default Case Owner.
  • When a workflow field update changes a record, the user is the Default Workflow User.
  • Some of the $User merge fields can be used in mobile configuration filters. For more information, see Merge Fields for Mobile Filter Criteria.

$User.UITheme and $User.UIThemeDisplayed

Description:These global merge fields identify the Salesforce look and feel a user sees on a given Web page.
The difference between the two variables is that $User.UITheme returns the look and feel set by the user, while $User.UIThemeDisplayed returns the actual look and feel. For example, a user may have the permissions to see the new user interface theme look and feel, but if they are using a browser that doesn't support that look and feel, $User.UIThemeDisplayed returns a different value.
Factors that affect the expected theme from displaying include the user agent of the browser and whether accessibility mode is enabled.
Use:Use these variables to identify the CSS used to render Salesforce web pages to a user. Both variables return one of the following values:
  • Theme1—Obsolete Salesforce theme
  • Theme2Salesforce theme used prior to Spring '10
  • PortalDefaultSalesforce Customer Portal theme
  • WebstoreSalesforce AppExchange theme
  • Theme3—Current Salesforce theme, introduced during Spring '10
VisualforceExample:The following example shows how you can render different layouts based on a user's theme:
<apex:page>
        <apex:pageBlock title="My Content" rendered="{!$User.UITheme == 'Theme2'}">
           // this is the old theme...
        </apex:pageBlock>

        <apex:pageBlock title="My Content" rendered="{!$User.UITheme == 'Aloha'}">
          //this is the new theme ...
        </apex:pageBlock>
</apex:page>
The section “Styling Visualforce Pages” in the Visualforce Developer's Guide provides more information on how to use these global variables.

$UserRole

Description:A global merge field type to use when referencing information about the current user's role. Role merge fields can reference information such as role name, description, and ID.
Use:
  1. Select the field type: $UserRole.
  2. Select a merge field such as $UserRole.Name.
Validation Rule Example:The validation rule formula below references the user role name to validate that a custom field called Discount Percent does not exceed the maximum value allowed for that role:
Discount_Percent__c >
   VLOOKUP($ObjectType.Role_Limits__c.Fields.Limit__c,
   $ObjectType.Role_Limits__c.Fields.Name,
   $UserRole.Name)
Visualforce Example:
{!$UserRole.LastModifiedById}
Tips:
  • The current user is the person changing the record that prompted the default value, validation rule, or other operation that uses these global merge fields.
  • When a Web-to-Case or Web-to-Lead process changed a record, the current user is the Default Lead Owner or Default Case Owner.
  • When a workflow field update changes a record, the user is the Default Workflow User.
Note
You cannot use the following $UserRole values in Visualforce:
  • CaseAccessForAccountOwner
  • ContactAccessForAccountOwner
  • OpportunityAccessForAccountOwner
  • PortalType

5 comments:

Unknown said...

Your posts is really helpful for me.Thanks for your wonderful post. I am very happy to read your post.

Salesforce Training

Unknown said...

you have providing useful coding's i love this post keep updates...
Salesforce training institute in Chennai

Unknown said...

Your blog is really awesome and I got some useful information from your blog. This is really useful for me. Thanks for sharing such a informative blog. Keep posting.

Regards..
Cloud Training in Chennai

Unknown said...

Nowadays, most of the businesses rely on cloud based CRM tool to power their business process. They want to access the business from anywhere and anytime. In such scenarios, salesforce CRM will ensure massive advantage to the business owners. Amazon Web Services Training in Chennai | Amazon Web Services Training

gowthunan said...

I’d like to write some material for your blog in exchange for a link back to mine. Please shoot me an email if interested. Thanks.
safety course in chennai