I am trying to extract picklist value from a custom object Product__c, but I am getting duplicate values in the dynamic picklist.

Controller Code

public class VFOnlineShoppingController {

    //variables for dynamic picklist on Product
    public List<SelectOption> prodList{get;set;}
    public Id selectedProducts{get;set;}  
    Set<string> products = new set<string>();

    //variables for name and phone on Contact
    public Contact con{get; set;}
    Id conId;

    public VFOnlineShoppingController(){
        con = new Contact();
        conId = apexpages.currentPage().getParameters().get('recId');

        prodList = new List<SelectOption>();
        prodList.add(new SelectOption('','None'));

        //fetching data for Contact
        if(conId != null){
            for(Contact c :[SELECT Name,Phone
                            FROM Contact
                            WHERE Id = :conId]){
                                con = c;

        for(Product__c tempVar :[SELECT Product_Family__c from Product__c]){

        //fetching data for picklist in Product
        for(Product__c prod :[SELECT Id,Product_Family__c
                              FROM Product__c]){

                                  prodList.add(new SelectOption(prod.Id,prod.Product_Family__c));



VisualForce Code

Name Phone

    <apex:outputLabel >Select Product</apex:outputLabel>
    <apex:selectList value="{!selectedProducts}" size="1">
        <apex:selectOptions value="{!prodList}" />


Please help me to restrict the values of the picklist to non-duplicate ones.

  • is it resolved? – Ratan Paul Aug 11 '18 at 13:13

I will try to update the code where you are preparing the picklist value i.e. prodList

Since any product can have any no of Product family that't why you are getting the duplicate values. I would suggest to use Map here inorder to avoid the duplicate values. In Map you have keep the Product family as key so that it should be assign duplicate.

like this.

Map<String, Id> mapProductFamilyToProductId = new Map<String, Id>();

for(Product__c tempVar :[SELECT Product_Family__c from Product__c]){
    mapProductFamilyToProductId.put(tempVar.Product_Family__c, tempVar.Id);

for(String productFamily: mapProductFamilyToProductId.KeySet()){
    prodList.add(new SelectOption(mapProductFamilyToProductId.get(productFamily),productFamily));

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.