Jump to:

10994 Posts in 2728 Topics by 1819 members

All other Modules

SilverStripe Forums » All other Modules » MultiSelectField pre-selected values fix

Discuss all other Modules here.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 1206 Views
  • rwestera
    Avatar
    Community Member
    3 Posts

    MultiSelectField pre-selected values fix Link to this post

    Hi, was running into problems with the MultiSelectField using pre-selected values. Applying the following fixes helped:

    Lines 39-42 of MultiSelectField.php:

    foreach($source as $index => $item) {
       $selected = (isset($value[$index])) ? 'selected="selected"' : ''; // added '="selected"', wasn't parsing
       $content .= "<option $selected value=\"$index\">".Convert::raw2xml($item)."</option>"; // converted $item to xml for parsing
    }

    Also worth having an example of how to pre-select values:

    new MultiSelectField('Fruit', 'Favorite Fruit', array('1'=>'apple','2'=>'pear'), array('1'=>true))

  • Xurk
    Avatar
    Community Member
    50 Posts

    Re: MultiSelectField pre-selected values fix Link to this post

    Thanks for posting about this problem, rwestera. Unfortunately, your fix didn't do the trick for me. For some reason, I can't seem to set the value of the MultiSelectField until after it has already been initialized, where it looks like this needs to be done during initialization.

    If I add a var_dump() to the Field() method in the MultiSelectField class for the selected values, it returns an empty array every time. But if I add the field using the following code:

    $oFields->addFieldToTab('Root.PreferredProducts', $oPreferredProducts = new MultiSelectField(
       'PreferredProducts',
       'Voorkeursproducten',
       $oProducts->map('ID', 'Title'),
       $aPreselectedProducts
    ));

    var_dump($oPreferredProducts->getSelected());


    The var_dump() returns an array with all of the options I passed (in $aPreselectedProducts), but they aren't selected at all in the HTML or on the screen!

    In the end I went the ugly route by using the following code:

    $jsSelectOptions = "";
    foreach ($oPreferredProducts as $oProduct) {
       // Ugly JS fix
       $jsSelectOptions .= "jQuery('#Root_PreferredProducts select.multiselect-unselected option[value=\"".$oProduct->ID."\"]').attr('selected', 'selected');".chr(10);
    }

    // Preselect all default products and fire the click event for the "Add" button
    Requirements::customScript("
       (function($) {
          ".$jsSelectOptions."
          $('#Root_PreferredProducts .multiselect-add').click();
       })(jQuery);
    ");

    1206 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.