Visualforce Lookup Field

I have seen that allot of people are struggling with creating lookup field in Salesforce. It is very easy by just referencing the child relationship id in an apex:Inputfield. See examples below:

When using a standard controller in your page you can do the following:

<apex:page standardcontroller="Contact">
<apex:form>
<apex:inputField value="{!Contact.OwnerId}"/>
<apex:inputField value="{!Contact.AccountId}"/>
</apex:form>
</apex:page>



<apex:page standardcontroller="Account">
<apex:form>
<apex:inputField value="{!Account.OwnerId}"/>
<apex:inputField value="{!Account.RecordTypeId}"/>
<apex:inputField value="{!Account.ParentId}"/>
</apex:form>
</apex:page>

When using a custom controller in your page you can do the following:


<apex:page controller="UserReassignController">
<apex:form>
User From <apex:inputField label="UserFrom" id="UserFrom" value="{!User.OwnerId}" required="true"/>
User To <apex:inputField label="UserTo" id="UserTo" value="{!User.OwnerId}" required="true"/>
<apex:commandButton action="{!ReassignAllAccountContactOpportunities}" value="Reassign"/>
</apex:form>
</apex:page>


public with sharing class UserReassignController {

   private Account userFromOwnerId = new Account();
    private Account userToOwnerId = new Account();
  
    public Account UserFrom { get
    {
        return userFromOwnerId;
    } 
    set
    {
        userFromOwnerId = value;
    } 
    }

    public Account UserTo { get
    {
         return userToOwnerId;
    } 
    set
    {
        userToOwnerId = value;
    }
    }
}

5 thoughts on “Visualforce Lookup Field

  1. Great article. Actually works. I’ve been looking for this solution for 2 years.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s