lookup –> picklist

Posted by in apex, salesforce, visualforce

I’ve had several clients “voice concerns” about Salesforce.com’s lookup functionality relative to user acceptance. Well, if you’re dealing with a relatively simple lookup table, you can override an object’s new/edit page with a Visualforce page and display the lookup field to the user as a picklist.

In the given example, the user is creating a new “Some_Object__c” record. The Some_Object__c object is very simple: it’s comprised of a standard name field and a custom lookup to another table called “Location__c”. Location__c is comprised of name, city, and state fields and there are only 8 rows in the table. Rather than having the user click the magnifying glass icon to lookup to the Location__c table, one can quite easily display a list of possible values to the user along with any other pertinent information (in this case, I’m displaying Location__c’s City__c and State__c fields as well).

public class SomeObjectExtension {
	private final ApexPages.standardController controller;
	private final Some_Object__c obj;

	public SomeObjectExtension(ApexPages.StandardController stdController) {
		this.controller = stdController;
		this.obj = (Some_Object__c)stdController.getRecord();
	}

	public SelectOption[] getLocationOptions() {
		SelectOption[] locations = new SelectOption[]{};
		locations.add(new SelectOption('','--None--'));
		for (Location__c l : [select id, name, city__c, state__c from location__c where isdeleted = false order by name]) {
			locations.add(new SelectOption(l.id, l.name + ' (' + l.city__c + ', ' + l.state__c + ')'));
		}
		return locations;
	}
}


<apex:page standardController="Some_Object__c" extensions="SomeObjectExtension" showHeader="false" >
<apex:sectionHeader title="Some Object Edit" subtitle="New Some Object" />
<apex:form id="someObjectForm">
<apex:pageBlock title="Some Object Edit" mode="edit">
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Some Object Information" columns="1">
<apex:inputField value="{!Some_Object__c.Name}" required="true"/>
<apex:pageBlockSectionItem >
<apex:outputLabel value="{!$ObjectType.Some_Object__c.fields.Location__c.label}" for="pLabel"/>
<apex:outputPanel styleClass="requiredInput" layout="block">
<apex:outputPanel styleClass="requiredBlock" layout="block"/>
<apex:actionRegion >
<apex:selectList id="locationLookupPicklist" value="{!Some_Object__c.Location__c}" size="1" rendered="true">
<apex:selectOptions value="{!locationOptions}"/>
</apex:selectList>
</apex:actionRegion>
</apex:outputPanel>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>