Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

All other Modules

Discuss all other Modules here.

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

MultiSelectField pre-selected values fix


Reply

2 Posts   1219 Views

Avatar
rwestera

23 February 2011 at 5:02pm Community Member, 3 Posts

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))

Avatar
Xurk

1 February 2012 at 4:29am (Last edited: 1 February 2012 4:31am), Community Member, 50 Posts

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);
");