0

In my visualforce page I have a field 'Fruits', which has 4 checkboxes 'Apple', 'Orange', 'Grapes', and 'Kiwi' as options under it. I can select multiple options. Now in my controller I want to save the selected values to a multiselect picklist 'Fruit__c' in the 'Tree__c' object. How can I do it?

1

Let's assume you have 4 boolean varialbes for each of the checkboxes in order to determine which one is selected:

public boolean apple {get; set;}
public boolean orange {get; set;}
public boolean grapes {get; set;}
public boolean kiwi {get; set;}

In your save method you can check which of the 4 is selected and build a semi-colon separated string with the values (it's how multi-select picklists store the values):

public void save()
{
    String selectedFruits = '';
    selectedFruits += apple == true ? 'Apple;' : '';
    selectedFruits += orange == true ? 'Orange;' : '';
    selectedFruits += grapes == true ? 'Grapes;' : '';
    selectedFruits += kiwi == true ? 'Kiwi;' : '';

    Tree__c treeRecord = new Tree__c();
    treeRecord.Fruit__c = selectedFruits;
    // set other fields
    insert treeRecord;
}
  • Thanks Bachovski! Good point to know, that multilist picklists are stored as semi-colon separated values. Now what if I have 15 options instead of 4? – Knowme Feb 3 '15 at 6:11
  • Same thing just keep appending to the string, having every selected value followed by a semi colon. Alternatively you can just expose that multipicklist field on the page and don't worry about all this. If you have limitations around that then have a look at this multi select component - github.com/metadaddy-sfdc/Visualforce-Multiselect-Picklist – Boris Bachovski Feb 3 '15 at 6:15
  • Got it, thanks! :) But in my real case, I have 4 such fields with 15 options each! I feel there should be an effective way to do this?? – Knowme Feb 3 '15 at 16:54
  • Also I think the whole scenario will give you a better understanding. So there is one more object called Earth__c, where these 4 fields with their options are defined. I created those 4 fields in Fruit__c. Now In my controller, I am getting the options for the fields in Fruit__c from the fields in Earth__c, and displaying them on the visualforce page. I want the selected values on the visualforce page to be saved in the fields on Fruit__c. Please let me know if you have more questions on this. – Knowme Feb 3 '15 at 17:06
  • @Knowme so does that mean that Earth__c and Fruit__c both fields have the same values? – Boris Bachovski Feb 3 '15 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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