[SalesForce] How to save checkbox values to a multiselect picklist

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?

Best Answer

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;
}