Skip to content

Commit

Permalink
Fix key casting in form_dropdown helper. (#5035)
Browse files Browse the repository at this point in the history
  • Loading branch information
sfadschm authored Aug 31, 2021
1 parent 3d6b3bd commit ab580ba
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
6 changes: 5 additions & 1 deletion system/Helpers/form_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''):
}
}

// standardize selected as strings, like the option keys will be.
// Standardize selected as strings, like the option keys will be
foreach ($selected as $key => $item) {
$selected[$key] = (string) $item;
}
Expand All @@ -308,6 +308,7 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''):
$form = '<select ' . rtrim(parse_form_attributes($data, $defaults)) . $extra . $multiple . ">\n";

foreach ($options as $key => $val) {
// Keys should always be strings for strict comparison
$key = (string) $key;

if (is_array($val)) {
Expand All @@ -318,6 +319,9 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''):
$form .= '<optgroup label="' . $key . "\">\n";

foreach ($val as $optgroupKey => $optgroupVal) {
// Keys should always be strings for strict comparison
$optgroupKey = (string) $optgroupKey;

$sel = in_array($optgroupKey, $selected, true) ? ' selected="selected"' : '';
$form .= '<option value="' . htmlspecialchars($optgroupKey) . '"' . $sel . '>' . $optgroupVal . "</option>\n";
}
Expand Down
28 changes: 28 additions & 0 deletions tests/system/Helpers/FormHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,34 @@ public function testFormDropdownUnselected()
$this->assertSame($expected, form_dropdown('cars', $options));
}

public function testFormDropdownKeyCasting()
{
$options = [
'Swedish Cars' => [
'1' => 'Volvo',
'2' => 'Saab',
],
2 => [
3 => 'Mercedes',
'4' => 'Audi',
],
];
$selected = [2];
$expected = <<<EOH
<select name="cars">
<optgroup label="Swedish Cars">
<option value="1">Volvo</option>
<option value="2" selected="selected">Saab</option>
</optgroup>
<optgroup label="2">
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</optgroup>
</select>\n
EOH;
$this->assertSame($expected, form_dropdown('cars', $options, $selected));
}

public function testFormDropdownInferred()
{
$options = [
Expand Down

0 comments on commit ab580ba

Please sign in to comment.