Hot Posts

6/recent/ticker-posts

Salesforce Picklist example

Picklist in Salesforce

Introduction to Picklists in Salesforce

A picklist is a fundamental feature in Salesforce that allows users to select values from a predefined list. In this article, we will explore the different types of picklists available in Salesforce and discuss their functions and benefits.

Types of Picklists

There are three main types of picklists in Salesforce:

  1. Standard Picklists:

    These are the most common type of picklists. They allow users to select a single value from a list of predefined options.

  2. Multi-select Picklists:

    Unlike standard picklists, multi-select picklists allow users to select multiple values from a list of options. This is useful when users need to choose more than one value for a particular field.

  3. Global Picklists:

    Global picklists are a special type of picklist that can be shared across multiple objects. They ensure consistency and data integrity by allowing administrators to define a set of values that can be used across different fields and objects.

Functions for Working with Picklists

When working with picklists in Salesforce, there are three main functions that can be used in formula fields:

  1. ISPICKVAL():

    This function is used to check if a picklist field has a specific value. It returns a Boolean value (true or false) based on the comparison.

  2. CASE():

    The CASE function allows you to perform conditional logic based on the value of a picklist field. It can be used to define different actions or outcomes based on the selected value.

  3. TEXT():

    The TEXT function is used to convert a picklist value into text format. This can be useful when you need to perform operations or comparisons with the picklist value as a string.

Creation of Picklist.

Here we are creating a Picklist for Country and Continent. A pick list is a field type that allows to contain values and pick one value.

Steps to create Picklist.

Setup => Build => Create => Objects => Custom field and Relationships => New => Picklist

Restricted Picklists

A restricted picklist is a type of picklist where the values are limited to only those defined by a Salesforce administrator. This ensures data integrity and prevents users from entering redundant or erroneous values through the API.

Global picklist value sets are always restricted picklists. They provide a centralized set of values that can be shared across different objects, ensuring consistency and accuracy in data entry.

Difference between standard and custom picklist in Salesforce

Custom picklist fields can be either controlling or dependent fields. Standard picklist fields can be controlling fields but not dependent fields.

Difference between static and dynamic picklist?

Static picklists draw their data from the Siebel list of values table, which is maintained by an administrator. The data in the list of values table is fairly static. Dynamic picklists draw their data from other user-maintained tables, such as S_CONTACT or S_ORG_EXT. The data of these tables is dynamic.

Can we create picklist in custom settings?

Go to the fields area of the object you want to create a picklist field for. In the custom fields related list, click New. Select Picklist or Picklist (Multi-Select), and then click Next. Enter a label for the picklist field.

Salesforce | Show the picklist field value of the custom object on the Visualforce page

We can show the picklist field value on Visualforce page in a selectlist ( dropdown) using the following code in the controller class:

  public class classname {
 public List<SelectOption> selectItemsList() {   
      List<SelectOption> selectOptions = new List<SelectOption>();
      Schema.DescribeFieldResult describeResult = CustomObject__c.PickListFieldName__c.getDescribe();
      List<Schema.PicklistEntry> pickListEntries = describeResult.getPicklistValues();
            
      for( Schema.PicklistEntry eachEntry : pickListEntries) {
         selectOptions.add(new SelectOption(eachEntry.getLabel(), eachEntry.getValue()));    
      }
      return selectOptions;
  }
}
  
  <apex:page controller=”classname”>
<apex:form>
<apex:selectList value=" " size="1" multiselect="false"  >
<apex:selectOptions value="{!selectItemsList}">
</apex:selectOptions>
</apex:selectList>
</apex:form>
</apex:page>
  

Custom picklist on a Salesforce Visualforce Page

VF Page

<apex:page tabStyle="Case" controller="customPicklist"> <apex:form > <apex:pageBlock title="Custom PickList Demo" id="out"> <apex:pageBlockButtons > <apex:commandButton value="Save" action="{!save}" rerender="out" status="actStatusId"/> <apex:actionStatus id="actStatusId"> <apex:facet name="start"> <img src="/img/loading.gif" /> </apex:facet> </apex:actionStatus> </apex:pageBlockButtons> <apex:pageBlockSection title="Custom Picklist Using selectList and selectOptions"> <apex:selectList value="{!selectedCountry2}" multiselect="false" size="1"> <apex:selectOptions value="{!countriesOptions}"/> </apex:selectList> <apex:outputText value="{!selectedCountry2}" label="You have selected:"/> </apex:pageBlockSection> </apex:pageBlock> <apex:pageBlock > </apex:pageBlock> </apex:form> </apex:page>
Apex Controller Class:
public with sharing class customPicklist {
public String selectedCountry2{get;set;}
public List<String> selectedCategories { get; set; }
public List<SelectOption> getCountriesOptions() {
List countryOptions = new List();
countryOptions.add(new SelectOption('','-None-'));
countryOptions.add(new SelectOption('INDIA','India'));
countryOptions.add(new SelectOption('USA','USA'));
countryOptions.add(new SelectOption('United Kingdom','UK'));
countryOptions.add(new SelectOption('Germany','Germany'));
countryOptions.add(new SelectOption('Ireland','Ireland'));
return countryOptions;
}
public List getCategories() {
List categories = new List();
for(Case c : [Select sahi__MultiSelectPicklist__c from Case limit 10])
categories.add(new SelectOption(c.sahi__MultiSelectPicklist__c, c.sahi__MultiSelectPicklist__c));
return categories;
}
public PageReference save(){
return null;
}
}

Another method

<apex:page controller="TestController ">
<apex:form >
<apex:selectList size="1" value="{!selectedname}">
<apex:selectOptions value="{!selectedaccnamefields}"/>
</apex:selectList>
</apex:form>
</apex:page>

public class TestController {
Public string selectedname{get;set;}
Public List<Selectoption> getselectedaccnamefields(){
List<Selectoption> lstnamesel = new List<selectoption>();
lstnamesel.add(new selectOption('', '- None -'));
for(Account acc :[SELECT id,name,phone,type,industry FROM Account]){
lstnamesel.add(new selectoption(acc.id,acc.name));
}
return lstnamesel;
}
}

Picklist Characteristics

  • Picklist values are static and cannot be defined dynamically.
  • Picklist values are maintained by the administrator.
  • Picklist values are displayed as a drop-down menu.
  • The maximum number of characters allowed in a picklist is 15,000.
  • A custom picklist can have up to 1,000 entries and 255 characters per entry.
  • A custom multi-select picklist can have up to 150 values and 40 characters per value.
  • For a multi-select picklist, users can select up to 100 values at a time on a record.
  • Picklists can have controlling and dependent picklists.
  • Picklist values do not have any other associated data.
  • Values are captured in Web-to-Lead submissions where Web-to-Lead does not support custom relationship fields.

Field Dependency.

Here, we want to establish the field dependency across the two fields Continent and Country.

Controlling Field: The value in dependency controls the value of the dependent field.

Dependency field: The vale on Dependency field depends on value of the Controlling field.

Now we are going to create Controlling field and Dependent field.

Go to Setup => Build => Create => Objects => Custom field ans Relationships => Field Dependency.

An example would be if you had a list of countries and states/provinces . If you select a country you would want the list of states/provinces to be filtered in the next picklist.

Visualforce page

<apex:page controller="DependentPicklistExpClass">
    <apex:form>
        <apex:pageblock>
            <apex:pageblocksection columns="2">
                <apex:pageblocksectionitem>
                    <apex:outputlabel value="Country">
                    </apex:outputlabel>
                </apex:pageblocksectionitem>
                <apex:pageblocksectionitem>
                    <apex:selectlist size="1" value="{!country}">
                        <apex:selectoptions value="{!countries}"></apex:selectoptions>
                        <apex:actionsupport event="onchange" rerender="a"></apex:actionsupport>
                    </apex:selectlist>
                </apex:pageblocksectionitem>
                <apex:pageblocksectionitem>
                    <apex:outputlabel value="State"></apex:outputlabel>
                </apex:pageblocksectionitem>
                <apex:pageblocksectionitem>
                    <apex:selectlist size="1" value="{!state}" id="a">
                        <apex:selectoptions value="{!states}"></apex:selectoptions>
                    </apex:selectlist>
                </apex:pageblocksectionitem>
            </apex:pageblocksection>
        </apex:pageblock>
    </apex:form>
</apex:page>

Apex Class

public class DependentPicklistExpClass {
    public String country{get;set;}
    public String state{get;set;}
    public List getCountries()
    {
        list options=new list();
        options.add(new SelectOption('none','countries'));
        options.add(new SelectOption('US','United States'));
        options.add(new SelectOption('IN','India'));
        return options;
    }
    public list getStates()
    {
        list options=new list();
        if(country=='US')
        {
            options.add(new SelectOption('none','states'));
            options.add(new SelectOption('st1','State1'));
            options.add(new SelectOption('st2','State2'));
        }
        else if(country=='IN')
        {
            options.add(new SelectOption('none','states'));
            options.add(new SelectOption('UP','Uttar Pradesh'));
            options.add(new SelectOption('UK','Uttarakhand'));
        }
        else
        {
            options.add(new SelectOption('none','states'));
        }
        return options;
    }
}

Multiselect Picklist Field:

In below example I’ve created a custom multiselect picklist “Interests” on “Student” custom object. I’m displaying multiselect picklist to checkboxes in visualforce page.

public class SampleControllerExtn {
    public Student__c student {get;set;}
    
    public SampleControllerExtn(ApexPages.StandardController stdCtrl) {
        student = (Student__c)stdCtrl.getRecord();
    }
    
    public void saveStudent(){
        Upsert student;
    }
    
    //get the multi-select pick list values
    public List<SelectOption> getMSPicklist {
        get {
            List<SelectOption> options = new List<SelectOption>();
            for( Schema.PicklistEntry obj : Student__c.Interests__c.getDescribe().getPicklistValues()) {
                options.add(new SelectOption(obj.getValue(), obj.getLabel()));
            } 
            return options;
        }  
        set;
    }
    
    //get and set the multi-select pick list as checkboxes
    public String[] MSItems { 
        get {
            List<String> selected = new List<String>();
            List<SelectOption> options = this.getMSPicklist;
            for(SelectOption obj : options) {
                if (this.student.Interests__c !=null && this.student.Interests__c.contains(obj.getValue()))
                    selected.add(obj.getValue());
            }
            return selected;
        }public set {
            String selectedCheckBox = '';
            for(String s : value) {
                if (selectedCheckBox == '') 
                    selectedCheckBox += s;
                else selectedCheckBox += ';' + s;
            }
            student.Interests__c = selectedCheckBox;
        }
    } 
}

Visualforce Page:

<apex:page standardController="Student__c" extensions="SampleControllerExtn" tabStyle="Student__c">
    <apex:form>
        <apex:pageBlock>
            <apex:pageblockSection title="Student Details" columns="1" collapsible="false">
                <apex:inputfield value="{!student.name}"/>
                <apex:selectcheckboxes layout="pageDirection"  value="{!MSItems}" label="Interests">                   
                    <apex:selectoptions value="{!getMSPicklist}"/>      
                </apex:selectcheckboxes>
            </apex:pageblockSection>
            <apex:pageblockButtons>
                <apex:commandButton value="Save" action="{!saveStudent}"/>                
            </apex:pageblockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:

Custom Multiselect Picklist Field in Visualforce Page

Controller:

public class SampleController {
    
    Set<String> picklistValues = new Set<String> {'New York','California','Texas','Los Angeles','Chicago','San Francisco', 'Washington'};
    Public List<String> leftSelected {get;set;}
    Public List<String> rightSelected {get;set;}
    Set<String> leftValues = new Set<String>();
    Set<String> rightValues = new Set<String>();
    
    public SampleController(){
        leftSelected = new List<String>();
        rightSelected = new List<String>();
        leftValues.addAll(picklistValues);
    }
    
    public PageReference getSelect(){
        rightSelected.clear();
        for(String s : leftSelected){
            leftValues.remove(s);
            rightValues.add(s);
        }
        return null;
    }
    
    public PageReference getDeselect(){    
        leftSelected.clear();
        for(String s : rightSelected){
            rightValues.remove(s);
            leftValues.add(s);
        }
        return null;
    }
    
    public List<SelectOption> getDeselectedValues(){
        List<SelectOption> options = new List<SelectOption>();
        List<String> objList = new List<String>();
        objList.addAll(leftValues);
        objList.sort();
        for(String s : objList){
            options.add(new SelectOption(s,s));
        }
        return options;
    }
    
    public List<SelectOption> getSelectedValues(){
        
        List<SelectOption> options = new List<SelectOption>();
        List<String> objList = new List<String>();
        objList.addAll(rightvalues);
        objList.sort();
        for(String s : objList){
            options.add(new SelectOption(s,s));
        }
        return options;
    }
}

Visualforce Page:

<apex:page controller="SampleController">
    <apex:form>
        <apex:panelGrid columns="3" id="abcd">
            <apex:selectList id="sel1" value="{!leftSelected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!DeselectedValues}" />
            </apex:selectList>
            
            <apex:panelGroup>
                <br/>
                <apex:image styleClass="picklistArrowRight" value="/s.gif">
                    <apex:actionSupport event="onclick" action="{!getSelect}" reRender="abcd"/>
                </apex:image>
                <br/><br/>
                <apex:image styleClass="picklistArrowLeft" value="/s.gif">
                    <apex:actionSupport event="onclick" action="{!getDeselect}" reRender="abcd"/>
                </apex:image>
            </apex:panelGroup>
            <apex:selectList id="sel2" value="{!rightSelected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!SelectedValues}" />
            </apex:selectList>
        </apex:panelGrid>
    </apex:form>
</apex:page>

Output:

Post a Comment

0 Comments