Blog has moved

New EDL Consulting Blog!

EDL Consulting has started a corporate blog (available at http://edlconsulting.com/blog) and I just posted my first blog there titled Faster VisualForce Translation.  Check it out.

I’m still planning on using this blog and whenever I do post something to the EDL blog, I plan on just posting the EDL link to serve as notification.  Re-posting the entire thing seems like more work than necessary, plus it’d violate the DRY principle.

Vote for my idea: Explain event which caused Org Admin Lock

VisualForce Internationalization Lessons Learned

As it relates to internationalization with VisualForce, I sometimes feel like a spelunker charting the depths of some mysterious cave.  The equivalent of the flashlight going out is realizing you’ve rolled something to production you thought was correctly internationalized but in fact, was not.  That’s happened to me one to many times in the last year or so and as a result, I’m going to do my best to pass along some of the lessons I’ve learned the hard way.

Beyond the basics of translating your static VisualForce content, I’ve observed two main hot-spots:

  1. Correctly setting the apex:page language attribute
  2. Referencing static content in Apex Controllers (as opposed to the VisualForce page)

For #1, I’ve developed a set of utility methods to make this much easier and placed them in a class called LanguageUtils.cls in apex-lang.  Want your VF page to be translated according to user’s browser settings?  No problem, simply use the getLangCodeByBrowser() method.  Or perhaps you want to allow an http parameter to be passed but in case that’s null, use the currently running user’s language?  Use method getLangCodeByHttpParamOrIfNullThenUser().  Trust me, there are hidden gems in these methods like defaulting zh to zh_CN.

For #2, this has been especially painful.  You might be tempted to say “dude, just don’t reference static content in Apex Controllers”; however, many times it’s not that simple.  You might have a design which is more efficient by referencing static content in an Apex Controller.  Or, like I’ve had, a product feature requirement which absolutely necessitated the need for it.  Regardless, developers need to be able to reference static content in Apex Controllers.  A good example where you can, but absolutely shouldn’t, is Custom Labels:  references to Custom Labels in an Apex Controller can ONLY be translated according to the language of currently running user.  No matter what value you throw in the apex:page language attribute, a label will only be translated according to the language of the currently running user.  I’ve submitted this as a defect to salesforce and I certainly hope they fix this soon.  The obvious workaround is to not reference them in an Apex Controller.  Unfortunately in this case, that’s the only option.

Another type of static content which is problematic is picklist values.  Picklist values can be retrieved in an Apex Controller via a describe.  The tricky part is, in order to control the translation via the apex:page language attribute, the describe cannot be done in the constructor for the page’s controller.  Instead, the describe must be done in an “onload” action method.  Here’s a demo of this issue via the following two links.  Both pages will be rendered in Simplified Chinese.

Link 1, picklist describe performed in constructor;  picklist will not be translated

Link 2, picklist describe performed in page onload action method;  picklist will be translated

apex-lang 1.8 released

New features include:

NumberUtils

  • toString() methods for printing out numbers in binary, octal, hex, etc.

LanguageUtils

getLangCodeByBrowserOrIfNullThenHttpParamgetLangCodeByBrowserOrIfNullThenHttpParam

VisualForce Pagination with apex-lang

Pagination in VisualForce is a frequently occurring requirement for force.com developers. While the platform includes a native api for pagination in the StandardSetController class, it’s fairly inflexible; especially for complex pagination. And just as important, the native api supports pagination with sObjects only, so if you want to show pages of “plain old apex objects”, you’re out of luck. (And in case you didn’t know, sObjects are NOT Objects in apex. This is very different from Java in that all classes inherit from Object in Java.)

UPDATE:  Starting in Spring ’10, an sObject can be referred to as an Object.

In this blog entry, I’ll introduce you to pagination in apex-lang via a concept called “paginators”. I’ll describe the design and then go through several examples of varying levels of difficulty which demonstrate how to effectively utilize a paginator.

There are two types of paginators in apex-lang, one for sObjects (SObjectPaginator) and one for “plain old apex objects (ObjectPaginator). The classes are essentially mirrors of each other; however, the redundancy is necessary (unfortunately) due to the fact that sObjects are not Objects in apex.

Once a paginator is constructed, your code will need to call the all-important setRecords() method in order to populate the paginator with data. Now comes the key part. The setRecords() method will invoke a handleNewPage() method on any “listeners” of the paginator. This means you’ll need to implement a handleNewPage() method in your code (and implement corresponding interface ObjectPaginatorListener or SObjectPaginatorListener) in order to receive page changes. The beauty of this design is the handleNewPage() method will also be called for user triggered events. These include the user clicking on standard pagination actions such as next, previous, last, etc. Paginators have these methods built-in and those methods can be bound directly on your page. Below is a sequence diagram which illustrates the interaction between the VisualForce page, controller, and paginator.

PaginatorInteraction

Note: It might seem you should be able to bind directly to the paginator’s page variable and implementing the handlePageChange method should be correspondingly optional as well. However, there’s another unfortunate Apex/VisualForce feature which prevents a VisualForce page from binding directly to the page variable on a paginator. To illustrate the issue, the following page & controller fails to execute.

1.  public class MyController{
2.      public List records {get;set;}
3.      public MyController(){
4.          records = [select id,name,industry from Account limit 100];
5.      }
6.  }
7.
8.  <apex:page>
9.      <apex:repeat value="{!records}" var="record">
10.         <apex:outputText value="{!record.industry}"><br/>
11.     </apex:repeat>
12. </apex:page>

The failure occurs at run-time on line 10 since record is of type sObject. sObjects do not contain a property called industry so the page fails. This means that to bind directly to named properties, your record must be of a concrete type. This necessitates the need for having code which uses a paginator to implement the handlePageChange() method. In this method, your code will need to perform a down-cast; the casting stinks but there’s really no other generic way of handling this.

On to the code examples!

First, let’s start with just about the simplest example possible. The below controller runs a SOQL query on Account and divides the results into pages of 15 records each via SObjectPaginator. The handlePageChange() method is called by the paginator as part of the setRecords() invocation as well as when the user clicks on the Next and Previous links.

Demo: http://rvdemo-developer-edition.na6.force.com/AccountPaginationDemo

<!-- ======================================================= -->
<!-- Controller -->
global class AccountPaginationDemo implements SObjectPaginatorListener {
	global List<Account> accounts {get;private set;}
	global SObjectPaginator paginator {get;private set;}
	global AccountPaginationDemo(){
		accounts = new List<Account>();
		//15 is pageSize, this refers to this class which acts as listener to paginator
		paginator = new SObjectPaginator(5,this);
		paginator.setRecords([select id,name from Account limit 100]);
	}
	global void handlePageChange(List<SObject> newPage){
		accounts.clear();
		if(newPage != null){
			for(SObject acct : newPage){
				accounts.add((Account)acct);
			}
		}
	}
}
<!-- Page: page -->
<apex:page showHeader="false" sidebar="false" standardStylesheets="true" controller="AccountPaginationDemo">
	<apex:composition template="DemoTemplate">
		<apex:define name="body">
			<apex:form >
			    <apex:pageBlock title="Accounts" id="accounts">
			        <apex:pageBlockTable value="{!accounts}" var="account">
						<apex:column >
							<apex:facet name="header">Name</apex:facet>
							<apex:outputPanel >{!account.name}</apex:outputPanel>
						</apex:column>
						<apex:facet name="footer">
							<apex:outputPanel >
								<apex:outputText value="Page {!paginator.pageNumberDisplayFriendly} of {!paginator.pageCount} in {!paginator.recordCount} Results"/>
								<apex:outputPanel >    </apex:outputPanel>
								<apex:commandLink value="Previous" action="{!paginator.previous}"
									rendered="{!IF(paginator.hasPrevious,'true','false')}"/>
								<apex:outputText value="Previous" rendered="{!IF(NOT(paginator.hasPrevious),'true','false')}"/>
								<apex:outputPanel > | </apex:outputPanel>
								<apex:commandLink value="Next" action="{!paginator.next}"
									rendered="{!IF(paginator.hasNext,'true','false')}"/>
								<apex:outputText value="Next" rendered="{!IF(NOT(paginator.hasNext),'true','false')}"/>
							</apex:outputPanel>
						</apex:facet>
			        </apex:pageBlockTable>
			    </apex:pageBlock>
			</apex:form>
		</apex:define>
	</apex:composition>
</apex:page>

The next example shows how a “run-time” property can be added to an sObject and the same basic paginator interface can be utilized via the Object paginator version as opposed to the sObject version. In the below controller, a “plain old apex object” called SelectableAccount is used to store both an Account and a Boolean flag representing whether or not the Account is selected (i.e. the “run-time” property). Instead of creating an SObjectPaginator, this example converts the retrieved Accounts into SelectableAccounts and creates an ObjectPaginator instead.

Demo: http://rvdemo-developer-edition.na6.force.com/SelectableAccountPaginationDemo

<!-- ======================================================= -->
<!-- Controller -->
global class SelectableAccountPaginationDemo implements ObjectPaginatorListener {
	global List<SelectableAccount> accounts {get;private set;}
	global ObjectPaginator paginator {get;private set;}
	global SelectableAccountPaginationDemo(){
		this.accounts = new List<SelectableAccount>();
		List<SelectableAccount> all = new List<SelectableAccount>();
		List<Account> records = [select id,name from Account limit 100];
		if(records != null){
			for(Account acct : records){
				all.add(new SelectableAccount(acct));
			}
		}
		//15 is pageSize, this refers to this class which acts as listener to paginator
		paginator = new ObjectPaginator(5,this);
		paginator.setRecords(all);
	}
	global void handlePageChange(List<Object> newPage){
		accounts.clear();
		if(newPage != null){
			for(Object acct : newPage){
				accounts.add((SelectableAccount)acct);
			}
		}
	}
	global class SelectableAccount{
		global Boolean selected{get;set;}
		global Account obj{get;set;}
		global SelectableAccount(Account obj){
			this.obj = obj;
		}
	}
}
<!-- Page: page -->
<apex:page showHeader="false" sidebar="false" standardStylesheets="true" controller="SelectableAccountPaginationDemo">
	<apex:composition template="DemoTemplate">
		<apex:define name="body">
			<apex:form >
			    <apex:pageBlock title="Accounts" id="accounts">
			        <apex:pageBlockTable value="{!accounts}" var="account">
						<apex:column >
							<apex:inputCheckbox value="{!account.selected}"/>
						</apex:column>
						<apex:column >
							<apex:facet name="header">Name</apex:facet>
							<apex:outputPanel >{!account.obj.name}</apex:outputPanel>
						</apex:column>
						<apex:facet name="footer">
							<apex:outputPanel >
								<apex:outputText value="Page {!paginator.pageNumberDisplayFriendly} of {!paginator.pageCount} in {!paginator.recordCount} Results"/>
								<apex:outputPanel >    </apex:outputPanel>
								<apex:commandLink value="Previous" action="{!paginator.previous}"
									rendered="{!IF(paginator.hasPrevious,'true','false')}"/>
								<apex:outputText value="Previous" rendered="{!IF(NOT(paginator.hasPrevious),'true','false')}"/>
								<apex:outputPanel > | </apex:outputPanel>
								<apex:commandLink value="Next" action="{!paginator.next}"
									rendered="{!IF(paginator.hasNext,'true','false')}"/>
								<apex:outputText value="Next" rendered="{!IF(NOT(paginator.hasNext),'true','false')}"/>
							</apex:outputPanel>
						</apex:facet>
			        </apex:pageBlockTable>
			    </apex:pageBlock>
			</apex:form>
		</apex:define>
	</apex:composition>
</apex:page>

The next and final example is quite a bit more complicated. The example allows browsing of all accounts and contacts. There are two result sets: an Account result set and a Contact result set. The currently selected Account and Contact is in bold and the corresponding record’s details are shown below. In essence, this is a “quick” view screen.

Demo: http://rvdemo-developer-edition.na6.force.com/PaginatorDemo

<!-- ======================================================= -->
global class PaginatorDemo {
	public List<AccountWrapper> accounts {get;set;}
	public SObjectPaginator acctPaginator{get;set;}
	public Account selectedAccount{get;set;}
	public List<ContactWrapper> contacts {get;set;}
	public SObjectPaginator contPaginator{get;set;}
	public Contact selectedContact{get;set;}

	public PaginatorDemo(){
		this.accounts = new List<AccountWrapper>();
		this.contacts = new List<ContactWrapper>();
		this.acctPaginator = new SObjectPaginator(5,new AccountListListener(this));
		this.contPaginator = new SObjectPaginator(5,new ContactListListener(this));
		this.acctPaginator.setRecords([select id,name from account]);
	}

	global void handleAccountListPageChange(List<SObject> newPage){
		this.accounts.clear();
		if(newPage != null && newPage.size() > 0){
			for(Integer i = 0; i < newpage.size(); i++){
				AccountWrapper acct = new AccountWrapper((Account)newPage.get(i));
				accounts.add(acct);
				acct.serialNumber = i + acctPaginator.pageStartPosition;
			}
			PageUtils.param('accountId',accounts.get(0).obj.id);
			handleAccountSelected();
		}
	}

	public PageReference handleAccountSelected(){
		String accountId = PageUtils.param('accountId');
		for(AccountWrapper acct : accounts){
			acct.selected = acct.obj.id == accountId;
			if(acct.selected){
				selectedAccount = acct.obj;
				this.contPaginator.setRecords([select id,name from contact where accountid = :acct.obj.id]);
			}
		}
		return null;
	}

	global void handleContactListPageChange(List<SObject> newPage){
		System.debug('new contact list page: ' + ArrayUtils.toString(newPage));
		this.contacts.clear();
		if(newPage != null && newPage.size() > 0){
			for(Integer i = 0; i < newpage.size(); i++){
				ContactWrapper cntct = new ContactWrapper((Contact)newPage.get(i));
				contacts.add(cntct);
				cntct.serialNumber = i + (contPaginator == null ? 0 : contPaginator.pageStartPosition);
			}
			Contact wrapper = (Contact)this.contacts.get(0).obj;
			if(wrapper != null){
				PageUtils.param('contactId',wrapper.id);
				handleContactSelected();
			}
		}
	}

	public PageReference handleContactSelected(){
		String contactId = PageUtils.param('contactId');
		for(ContactWrapper contact : contacts){
			contact.selected = contact.obj.id == contactId;
			if(contact.selected){
				selectedContact = contact.obj;
			}
		}
		return null;
	}

	global class AccountListListener implements SObjectPaginatorListener {
		private PaginatorDemo controller;
		global AccountListListener(PaginatorDemo controller){
			this.controller = controller;
		}
		global void handlePageChange(List<SObject> newPage){
			controller.handleAccountListPageChange(newPage);
		}
	}

	global class ContactListListener implements SObjectPaginatorListener {
		private PaginatorDemo controller;
		global ContactListListener(PaginatorDemo controller){
			this.controller = controller;
		}
		global void handlePageChange(List<SObject> newPage){
			controller.handleContactListPageChange(newPage);
		}
	}

	public class AccountWrapper{
		public Account obj{get;set;}
		public Integer serialNumber{get;set;}
		public Boolean selected{get;set;}
		public AccountWrapper(Account obj){
			this.obj = obj;
		}
	}

	public class ContactWrapper{
		public Contact obj{get;set;}
		public Integer serialNumber{get;set;}
		public Boolean selected{get;set;}
		public ContactWrapper(Contact obj){
			this.obj = obj;
		}
	}
}
<!-- ======================================================= -->
<apex:page showHeader="false" sidebar="false" standardStylesheets="true" controller="PaginatorDemo">
	<apex:form >
		<p>
			<apex:actionStatus startStyle="color: #F00; font-weight: bold;" startText="Updating...." stopText="" id="updateStatus"/>
		</p>
		<table width="100%" border="0" cellpadding="3" cellspacing="0">
			<tr>
				<td valign="top" width="50%">
				    <apex:pageBlock title="Accounts {!acctPaginator.pageStartPositionDisplayFriendly} - {!acctPaginator.pageEndPositionDisplayFriendly} of {!acctPaginator.recordCount}" id="accounts">
				        <apex:pageBlockTable value="{!accounts}" var="account">
							<apex:column >
								<apex:facet name="header">#</apex:facet>
								<apex:outputText value="{!account.serialNumber+1}"/>
							</apex:column>
							<apex:column >
								<apex:facet name="header">Name</apex:facet>
								<apex:outputPanel rendered="{!account.selected}"><b>{!account.obj.name}</b></apex:outputPanel>
								<apex:commandLink rendered="{!NOT(account.selected)}" action="{!handleAccountSelected}" value="{!account.obj.name}"
									 reRender="accounts,contacts,accountDetail,contactDetail" status="updateStatus">
									<apex:param name="accountId" value="{!account.obj.id}"/>
								</apex:commandLink>
							</apex:column>
							<apex:facet name="footer">
								<apex:outputPanel >
									<apex:commandLink action="{!acctPaginator.first}" value="<< First"
										reRender="accounts,contacts,accountDetail,contactDetail" status="updateStatus"/>

									<apex:outputPanel > | </apex:outputPanel>
									<apex:commandLink action="{!acctPaginator.previous}" rendered="{!acctPaginator.hasPrevious}"
										value="< Previous" reRender="accounts,contacts,accountDetail,contactDetail" status="updateStatus"/>
									<apex:outputText rendered="{!NOT(acctPaginator.hasPrevious)}"
										value="< Previous"/>

									<apex:outputPanel > | </apex:outputPanel>

									<apex:commandLink action="{!acctPaginator.next}" rendered="{!acctPaginator.hasNext}"
										value="Next >" reRender="accounts,contacts,accountDetail,contactDetail" status="updateStatus"/>
									<apex:outputText rendered="{!NOT(acctPaginator.hasNext)}"
										value="Next >" />

									<apex:outputPanel > | </apex:outputPanel>

									<apex:commandLink action="{!acctPaginator.last}" value="Last >>" reRender="accounts,contacts,accountDetail,contactDetail"
										status="updateStatus"/>
								</apex:outputPanel>
							</apex:facet>
				        </apex:pageBlockTable>
				    </apex:pageBlock>
					<apex:outputPanel id="accountDetail">
						<apex:detail subject="{!selectedAccount.id}" relatedList="false" title="false"/>
					</apex:outputPanel>
				</td>
				<td valign="top" width="50%">
				    <apex:pageBlock title="Contacts {!contPaginator.pageStartPositionDisplayFriendly} - {!contPaginator.pageEndPositionDisplayFriendly} of {!contPaginator.recordCount}" id="contacts">
				        <apex:pageBlockTable value="{!contacts}" var="contact">
							<apex:column >
								<apex:facet name="header">#</apex:facet>
								<apex:outputText value="{!contact.serialNumber+1}"/>
							</apex:column>
							<apex:column >
								<apex:facet name="header">Name</apex:facet>
								<apex:outputPanel rendered="{!contact.selected}"><b>{!contact.obj.name}</b></apex:outputPanel>
								<apex:commandLink rendered="{!NOT(contact.selected)}" action="{!handleContactSelected}" value="{!contact.obj.name}"
									 reRender="contacts,contactDetail" status="updateStatus">
									<apex:param name="contactId" value="{!contact.obj.id}"/>
								</apex:commandLink>
							</apex:column>
							<apex:facet name="footer">
								<apex:outputPanel id="contactsLinks">
									<apex:commandLink action="{!contPaginator.first}" value="<< First"
										reRender="contacts,contactDetail" status="updateStatus"/>

									<apex:outputPanel > | </apex:outputPanel>
									<apex:commandLink action="{!contPaginator.previous}" rendered="{!contPaginator.hasPrevious}"
										value="< Previous" reRender="contacts,contactDetail" status="updateStatus"/>
									<apex:outputText rendered="{!NOT(contPaginator.hasPrevious)}"
										value="< Previous"/>

									<apex:outputPanel > | </apex:outputPanel>

									<apex:commandLink action="{!contPaginator.next}" rendered="{!contPaginator.hasNext}"
										value="Next >" reRender="contacts,contactDetail" status="updateStatus"/>
									<apex:outputText rendered="{!NOT(contPaginator.hasNext)}"
										value="Next >" />

									<apex:outputPanel > | </apex:outputPanel>

									<apex:commandLink action="{!contPaginator.last}" value="Last >>" reRender="contacts,contactDetail"
										status="updateStatus"/>
								</apex:outputPanel>
							</apex:facet>
				        </apex:pageBlockTable>
				    </apex:pageBlock>
					<apex:outputPanel id="contactDetail">
						<apex:detail subject="{!selectedContact.id}" relatedList="false" title="false"/>
					</apex:outputPanel>
				</td>
			</tr>
		</table>				

	</apex:form>
</apex:page>

Getting started with apex-lang

First, what is apex-lang?

apex-lang is an open-source library of helper classes written purely in apex whose goal is to address shortcomings in the core apex classes.  (If you’re not familiar with apex, apex is the programming language provided by salesforce.com’s development platform and is essentially a trimmed down version of java with added syntax for exploiting the force.com platform.)

apex-lang was inspired by the Apache Commons Lang project whose creators had a similar goal of addressing gaps in java’s core API.  apex is fairly feature rich;  however, let’s face it, functionality in its core API is sorely lacking.  And why shouldn’t it?  salesforce.com is in the “on-demand platform” business, not the API building business.  On the other hand, apex-lang is very much in the API building (not for profit) business. So, its the intent of apex-lang to fill in the gaps in the core apex classes.  And to fill them more quickly than salesforce can.  Salesforce only has 3-4 releases a year;  in contrast, apex-lang can be released as many times as needed during a single year.

Installing apex-lang

There are a couple of ways you can install apex-lang.

Option 1: Install the Unmanaged Package

1)  Go to http://code.google.com/p/apex-lang/

2)  Click on the Install link

apex-lang home

apex-lang home

3)  Enter your username and password for your salesforce org (obviously, do this in a sandbox or DE org first)

4)  Click Continue.

5)  On “Step 1. Approve Package API Access”, click Next

6)  On “Step 2. Choose security level”, select “Grant access to all users”

7)  On “Step 3. Install package”, click Install.  After a few moments, installation should be complete.

Option 2: Download and import into Force.com IDE

1)  Open Force.com IDE

2)  Select your project and expand the classes folder

Classes folder

Classes folder

3)  Go to http://code.google.com/p/apex-lang/

4)  Click on the Download link

5)  Save and then extract the apex-lang source zip file to your hard drive

6)  Open the extracted folder in Windows Explorer.

7)  Select all files (including the *-meta.xml files).

8)  Drag and drop the files into your project’s class folder in the Force.com IDE.  This should trigger the Force.com IDE to save the classes locally as well as to your salesforce org.

Dragging the source files into Force.com IDE

Dragging the source files into Force.com IDE

Utilizing apex-lang

The easiest way kick apex-lang’s tires is to log into your salesforce org and click on the “System Log” link in the top right corner of the screen.  This will open up a screen which will allow you to execute anonymous apex.  Simply copy and paste the following code into the lower text box and click “Execute Apex >>”.

System.debug(StringUtils.abbreviate('A string to abbreviate.',8));
System.debug(StringUtils.rightPad('Test',10,'X'));
System.debug(ArrayUtils.toString(new String[]{'Test','10','X'}));
System.debug(ArrayUtils.toString(new Double[]{1.2,3.4,5.6}));

Kicking the tires via Anonymous Execution

Kicking the tires via Anonymous Execution

To understand what functionality is available in apex-lang, review the Test classes.   They’re the best examples since every class and method is covered 100% by the test code.  And they don’t just cover the code, it truly tests the code via many, many asserts.   The StringUtils class contains so much code that the corresponding test class had to be broken into two test classes TestStringUtils and TestStringUtils2.   To more fully understand available methods, you’ll want to refer to the Apache Commons Lang Javadoc.

Follow

Get every new post delivered to your Inbox.