Skip to content

Commit ab580ba

Browse files
authored
Fix key casting in form_dropdown helper. (#5035)
1 parent 3d6b3bd commit ab580ba

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

system/Helpers/form_helper.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''):
298298
}
299299
}
300300

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

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

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

320321
foreach ($val as $optgroupKey => $optgroupVal) {
322+
// Keys should always be strings for strict comparison
323+
$optgroupKey = (string) $optgroupKey;
324+
321325
$sel = in_array($optgroupKey, $selected, true) ? ' selected="selected"' : '';
322326
$form .= '<option value="' . htmlspecialchars($optgroupKey) . '"' . $sel . '>' . $optgroupVal . "</option>\n";
323327
}

tests/system/Helpers/FormHelperTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,34 @@ public function testFormDropdownUnselected()
435435
$this->assertSame($expected, form_dropdown('cars', $options));
436436
}
437437

438+
public function testFormDropdownKeyCasting()
439+
{
440+
$options = [
441+
'Swedish Cars' => [
442+
'1' => 'Volvo',
443+
'2' => 'Saab',
444+
],
445+
2 => [
446+
3 => 'Mercedes',
447+
'4' => 'Audi',
448+
],
449+
];
450+
$selected = [2];
451+
$expected = <<<EOH
452+
<select name="cars">
453+
<optgroup label="Swedish Cars">
454+
<option value="1">Volvo</option>
455+
<option value="2" selected="selected">Saab</option>
456+
</optgroup>
457+
<optgroup label="2">
458+
<option value="3">Mercedes</option>
459+
<option value="4">Audi</option>
460+
</optgroup>
461+
</select>\n
462+
EOH;
463+
$this->assertSame($expected, form_dropdown('cars', $options, $selected));
464+
}
465+
438466
public function testFormDropdownInferred()
439467
{
440468
$options = [

0 commit comments

Comments
 (0)