[SalesForce] Create VisualForce input that uses Lookup popup

I have a custom object, Foobar__c, and I would like to create a VisualForce page containing a form in which the user has to select a Foobar__c via the standard Lookup popup for Foobar__c. I would ideally like the input for this field to be styled with the magnifying glass icon to the right of it, just like the user would see if they were editing an object that has a Foobar__c field.

I know that if I make an inputField whose value is a property of type Foobar__c of some other custom object, then Salesforce will automatically figure out that it needs to create a Foobar__c lookup input.

However, in my case the field being set by the input is not a property of some other custom object; it is simply a property of the page's Apex controller, which will be used when the form is saved. Trying to set the value input of the inputField to this property simply gives me the error message:

Could not resolve the entity from apex:inputField value binding '{!foobar}'. apex:inputField can only be used with SObjects, or objects that are Visualforce field component resolvable.

How can I create a custom object Lookup input for straightforward controller property, rather than for a property of a Salesforce object?

Best Answer

Per Jeff Douglas's ROLL YOUR OWN SALESFORCE "LOOKUP" POPUP WINDOW blog post, one way to do this is to simply create a dummy instance of an object that has a relationship with the one you want to perform a lookup on, and then use the appropriate property of that instance as the value of an inputField.

From his post:

MyCustomLookupController

Here's the Apex controller for the record you are either creating or editing. This is an extremely simple controller that just creates a new contact so you can use the lookup for the related account field.

public with sharing class MyCustomLookupController {

  public Contact contact {get;set;}

  public MyCustomLookupController() {
    contact = new Contact();
  }

}

MyCustomLookup

[ ... lots of code omitted; see the original post for full content ... ]

<apex:inputField id="Account" value="{!contact.AccountId}"/>

This is an ugly, hacky solution, and I'd hoped to find something cleaner, but it works. It'd be even uglier if you didn't already have an object with a field of the right type; in that case, I guess you could create a custom object whose entire purpose was to be used for this hack.

Related Topic