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

Style in LWC

 Following are the ways we can apply in CSS in LWC. 1. Inline CCS Inline CSS is not recommended approaches, it is take highest priority among all CSS. style="color:green;font-size:10px;" is inline CSS added to div < template >     < lightning-card title = "Inline CSS" >         < div >             < div style = "color:green;font-size:10px;" > This is inline Style div </ div >         </ div >     </ lightning-card > </ template >  2. External CSS style can be applied to an elements such as h1, p,div span etc. It can applied to class using "." notation. for example .user{} It can also be applied to pseudo class.  for example .user:hover{} Id locator is not being used in LWC to apply style To apply external css, need to create separate CSS file, file name should be exactly matched with component name. for example - If component name is ...

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 (); //...