Skip to content

Commit 2edbd6c

Browse files
committed
SelectBox: prompt key is always unique
1 parent 066a21b commit 2edbd6c

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/Forms/Controls/SelectBox.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,14 +90,22 @@ public function setItems(array $items, bool $useKeys = true)
9090

9191
public function getControl(): Nette\Utils\Html
9292
{
93-
$items = $this->prompt === false ? [] : ['' => $this->translate($this->prompt)];
93+
$items = [];
9494
foreach ($this->options as $key => $value) {
9595
$items[is_array($value) ? $this->translate($key) : $key] = $this->translate($value);
9696
}
9797

9898
$attrs = $this->optionAttributes;
9999
$attrs['disabled:'] = is_array($this->disabled) ? $this->disabled : null;
100100

101+
if ($this->prompt !== false) {
102+
$promptKey = '';
103+
while (isset($items[$promptKey])) {
104+
$promptKey .= "\x1";
105+
}
106+
$items = [$promptKey => $this->translate($this->prompt)] + $items;
107+
}
108+
101109
return Nette\Forms\Helpers::createSelectBox($items, $attrs, $this->value)
102110
->addAttributes(parent::getControl()->attrs);
103111
}

tests/Forms/Controls.SelectBox.render.phpt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,20 @@ test('selected 2x', function () {
6161
});
6262

6363

64+
test('unique prompt', function () {
65+
$form = new Form;
66+
$input = $form->addSelect('list', 'Label', [
67+
'' => 'First',
68+
])->setPrompt('prompt');
69+
70+
Assert::same('<select name="list" id="frm-list"><option value="' . "\x01" . '">prompt</option><option value="">First</option></select>', (string) $input->getControl());
71+
72+
$input->setValue('');
73+
74+
Assert::same('<select name="list" id="frm-list"><option value="' . "\x01" . '">prompt</option><option value="" selected>First</option></select>', (string) $input->getControl());
75+
});
76+
77+
6478
test('translator & groups', function () {
6579
$form = new Form;
6680
$input = $form->addSelect('list', 'Label', [

0 commit comments

Comments
 (0)