0

I have a checkbox field that is populate with user choices. I need to get the values they have selected from within a plugin. Here is my attempt. Not working.

    $entry  = craft()->entries->getEntryById($entryId, $localeId = null);
    foreach ($entry->storyCategories->options as $option) {
     var_dump($option);
    }

Can somebody please show me how to get these selected values?

5

You can pull an array of all the options for a checkbox field by calling getOptions():

$options = $entry->storyCategories->getOptions();

Each option will be an object with three properties, label, value and selected. To get all selected options for a field, you can loop through the options and test for the selected property:

$options = $entry->storyCategories->getOptions();
$selectedOptions = array();
foreach ( $options as $option ) {
    if ( $option->selected ) {
        $selectedOptions[] = $option;
    }
}

Note that this exact code will work for Dropdown, Multi-select and Radio button fields as well.

2
  • A quick followup question. If I were to make a change to the selected value and push it back into craft via plugin logic, am I storing a json object? Apr 7 '15 at 0:36
  • @DavidAaronMcInnis The values are technically stored in the database as a serialized array (see the column field_storyCategories in the database table craft_content, but as long as you use the EntriesService there's no JSON involved in the transport, no. If you have any other questions regarding updating entries/fields etc. it would probably be best to create a new question :) Apr 7 '15 at 7:48

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.