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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

All other Modules /

Discuss all other Modules here.

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

MultiSelectField pre-selected values fix


Go to End


2 Posts   2241 Views

Avatar
rwestera

Community Member, 3 Posts

23 February 2011 at 5:02pm

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

Community Member, 50 Posts

1 February 2012 at 4:29am

Edited: 01/02/2012 4:31am

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