Skip to main content

Salesforce: Custom Picklist in Visualforce Page

Suppose we are going to design a visualforce page and we add a picklist for users on the page. If the field where you want to store the selection is a picklist datatype then there is no problem we can do that by using <apex:selectList>.It is easy because  the field definition will define that ,the page will display a picklist when the Visualforce page is rendered.However, let's say that you want to display a picklist option based on a query from another object.
How would you do that ?.
It can be done by using look up field.we will make two object related by lookup relationship. When your user goes to use the lookup on the page, it opens a new window from which the user can search for records and then select one to populate back to the page.It will take more time to search . I was simply trying to limit the number and type of records that a relationship field made available to the user. I wanted to limit that functionality so that only specific records were permitted in the popup but still enforce the relationship integrity.
In this sample code I am going to make a Visualforce page to allow for editing of Contact records. However, I am going to create picklist options for the Account Name field instead of letting the user  to use Account Name the standard lookup functionality. So let us get into the code.

VisualForce Page
<apex:page StandardController="Contact" extensions="contactExtension"    standardStylesheets="true">

  <apex:sectionHeader title="Contact Edit" subtitle="{!Contact.Name}"    help="/help/doc/user_ed.jsp?loc=help">
   </apex:sectionHeader>
   <apex:form >
    <apex:pageBlock title="Contact Edit" mode="edit">
      <apex:pageBlockButtons >
         <apex:commandButton action="{!save}" value=" Save "></apex:commandButton>
         <apex:commandButton action="{!cancel}" value="Cancel"></apex:commandButton>
      </apex:pageBlockButtons>
      <apex:pageBlockSection title="General Information" columns="2">
        <apex:inputField value="{!Contact.FirstName}"></apex:inputField>
        <apex:inputField value="{!Contact.LastName}"></apex:inputField>
        <apex:inputField value="{!Contact.Department}"></apex:inputField>
        <apex:inputField value="{!Contact.Phone}"></apex:inputField>
        <apex:inputField value="{!Contact.Email}"></apex:inputField>
     </apex:pageBlockSection>
     <apex:pageBlockSection columns="1" showHeader="false">
       <apex:pageBlockSectionItem >
          <apex:outputLabel value="Account Name" for="accts"></apex:outputLabel>
          <apex:selectList id="accts" value="{!Contact.AccountId}" size="1" title="Account">
            <apex:selectOptions value="{!accts}"></apex:selectOptions>
          </apex:selectList>
       </apex:pageBlockSectionItem>
      </apex:pageBlockSection>
    </apex:pageBlock>
 </apex:form>
</apex:page>
My Controller:-
public class contactExtension {
    private final Contact c; //User sobject
    
    /*initializes the private member variable u by using the getRecord method from the standard controller*/
    public contactExtension(ApexPages.StandardController stdController) {
        this.c = (Contact)stdController.getRecord();
    }
    
    //builds a picklist of account names based on their account id
    public List<selectOption> getaccts() {
        List<selectOption> options = new List<selectOption>(); 
    //new list for holding all of the picklist options
        options.add(new selectOption('', '- None -')); 
    /*add the first option of '- None -' in case the user doesn't want to select a value or in       case no values are returned from query below*/
        for (Account account : [SELECT Id, Name FROM Account]) {  
   //query for Account records           
         options.add(new selectOption(account.id, account.Name));     
   //for all records found - add them to the picklist options       
      }       
      return options; //return the picklist options    }
}



Comments

Unknown said…
This post is real helpful for all Salesforce Developers

Popular posts from this blog

How to Create a Tooltip in Lightning Datatable ?

Imagine you have a datatable displaying a list of Contact records , and one of the columns shows the Account Name . The Account Name is a hyperlink that allows users to navigate to the Account record page. But what if users want to take a quick glance at some key Account fields —like Phone or Address—without navigating to the Account record? In Salesforce Classic, this was achieved using the Mini Page Layout feature from standard page. However, in Lightning Experience, we can implement a similar feature by adding a tooltip to the data table. Solution Overview: We’ll create a Lightning Web Component (LWC) that: Displays a data table with a clickable Account Name . Provides a tooltip that shows the Account's Phone and Address fields when users hover over the Account Name. Implementation Steps: 1. Data Preparation We need to retrieve the following fields for each Contact and its associated Account: Contact Fields : Name, Phone, Email Account Fields : Name, Phone, Billing Addre...

How to Create/Delete file attachments(Content Document) through Apex ?

 There are 3 standard salesforce objects to store file attachments. Content Document, ContentDocumentVersion, ContentDocumentLink.  Here is the article to talk about these objects and relationship.  https://www.forcetalks.com/blog/contentdocument-and-contentversion-in-salesforce-an-overview/ ContentDocumentVersion ContentDocumentLink This post is all about how to create/delete content document though Apex. Here is code snippet // Insert Content Version record ContentVersion contentVersionRec = new ContentVersion(Title='filename',PathOnClient ='FileName.pdf',VersionData = bodyBlob,origin = 'H'); INSERT contentVersionRec; // this will insert one record in ContentDocument and ContentVersion , ContentDocument  is parent and  ContentVersion is child record // get contentdocument id contentVersionRec = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :contentVersionRec .Id LIMIT 1]; // Create Content Document Link record- This will attach ...

Lifecycle hooks in LWC

There are 3 phase of LWC component  1. Mounting  A. constructor, B. connnectedCallback C. render D. renderedCallback 2. UnMounting  A. disconnectedcallback 3. Error  A.errorcallback Note - render is not lifecycle hook, it is protected method of Lightning element class. Mounting Phase LWC Creation and Render Life cycle Constructor Method ·        This method called when component is instantiated and It flows from parent to child component. ·        Need to call Super() inside constructor method ·        Can’t access any component properties or child component because it’s not ready yet. ·        Host element can be accessed through “this. template” inside constructor method. ·        Don’t add any attributes to host inside constructor C   constructor (){          super (); //...