Skip to content

Commit de4ba5a

Browse files
bartko-sdg
authored andcommitted
SelectBox: correctly selects prompt [Closes #343]
1 parent 64f4624 commit de4ba5a

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/Forms/Controls/SelectBox.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,8 @@ public function getControl(): Nette\Utils\Html
107107
$items = [$promptKey => $this->translate($this->prompt)] + $items;
108108
if ($this->isRequired()) {
109109
$attrs['hidden:'][$promptKey] = $attrs['disabled:'][$promptKey] = true;
110-
$selected ??= $promptKey; // disabled & selected for Safari, hidden for other browsers
110+
// disabled & selected for Safari, hidden for other browsers
111+
$selected = array_key_exists($this->value, $this->getItems()) ? $this->value : $promptKey;
111112
}
112113
}
113114

tests/Forms/Controls.SelectBox.render.phpt

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,36 @@ test('required select with prompt', function () {
9191
});
9292

9393

94+
test('select with prompt and invalid selected value', function () {
95+
$form = new Form;
96+
$input = $form->addSelect('list', 'Label', [
97+
'a' => 'First',
98+
0 => 'Second',
99+
])->setPrompt('prompt')->checkDefaultValue(false);
100+
101+
Assert::same('<select name="list" id="frm-list"><option value="">prompt</option><option value="a">First</option><option value="0">Second</option></select>', (string) $input->getControl());
102+
103+
$input->setValue('does not exists');
104+
105+
Assert::same('<select name="list" id="frm-list"><option value="">prompt</option><option value="a">First</option><option value="0">Second</option></select>', (string) $input->getControl());
106+
});
107+
108+
109+
test('required select with prompt and invalid selected value', function () {
110+
$form = new Form;
111+
$input = $form->addSelect('list', 'Label', [
112+
'a' => 'First',
113+
0 => 'Second',
114+
])->setPrompt('prompt')->setRequired()->checkDefaultValue(false);
115+
116+
Assert::same('<select name="list" id="frm-list" required data-nette-rules=\'[{"op":":filled","msg":"This field is required."}]\'><option value="" disabled hidden selected>prompt</option><option value="a">First</option><option value="0">Second</option></select>', (string) $input->getControl());
117+
118+
$input->setValue('does not exists');
119+
120+
Assert::same('<select name="list" id="frm-list" required data-nette-rules=\'[{"op":":filled","msg":"This field is required."}]\'><option value="" disabled hidden selected>prompt</option><option value="a">First</option><option value="0">Second</option></select>', (string) $input->getControl());
121+
});
122+
123+
94124
test('empty value and prompt', function () {
95125
$form = new Form;
96126
$input = $form->addSelect('list', 'Label', [

0 commit comments

Comments
 (0)