Monday, December 12, 2016

Visualforce - Beyond Basics Series 18 - Use Variables in Page

How to use variables in page ?

Visualforce page/component can use,

  •   global variables
  •   Functions
  •   parameters from controller/extensions
  •   local variables

I haven't seen many developers using variables that often. It's created using variable tag. It could be used when you have a very lengthy variable names (or) complex Function output (or) lengthy relationship chain to access parameters in controller/extension.

What is the advantage of it ?

It has all the advantages that a variable has in a programming language.

  •    A common place to access it's value
  •    No need to change it in all the place, if we ever want to change it
  •    We can give a meaningful variable name
  •    Code looks clean
  •    Improve maintainablity


How to use them dynamically ?

We could either assign the variable name statically like this,
<apex:variable value="{!$CurrentPage.Name}" var="current_page_name"/>
or dynamically like this which means the varname could be any value dynamically assigned from anywhere.
<apex:variable value="{!$CurrentPage.Name}" var="{!varname}"/>

Where is the code ?

This is the illustration of showing static variable assignment. 'TodaysDate' is a controller parameter. But, you can dynamically, changes its value in the component using  variable assignment. you can see that in the code below,



public class testcls5_12122016 {
public Date TodaysDate { get; set;}
public testcls5_12122016() {
TodaysDate = System.Today();
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
<apex:component >
<apex:attribute type="string" name="var" description="variable name"/>
<!-- Dynamic variable Name -->
<apex:variable var="{!var}" value="This is dummy value"/>
<apex:componentBody/>
</apex:component>
view raw gistfile1.txt hosted with ❤ by GitHub
<apex:page controller="testcls5_12122016">
<!-- Static variable Name -->
<apex:variable var="currentpage" value="{!$CurrentPage.Name}"/>
<!-- Output to User -->
Current page is - {!currentpage}
<!-- Dynamic variable Name -->
<c:testcmp5_12122016 var="TodaysDate">
Today's Date is {!TodaysDate}
</c:testcmp5_12122016>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment

Thanks for reading my blog !