Skip to content

Commit 9648c12

Browse files
authored
Merge pull request #6556 from WoltLab/62-select-form-field-default-value
Add an optional default value for `SelectFormField`
2 parents 48aa2fc + 48c57c1 commit 9648c12

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

com.woltlab.wcf/templates/shared_selectFormField.tpl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
required
99
{/if}
1010
>
11-
<option value="">{lang}wcf.global.noSelection{/lang}</option>
11+
{if !$field->hasDefaultValue()}
12+
<option value="">{lang}wcf.global.noSelection{/lang}</option>
13+
{/if}
1214
{foreach from=$field->getNestedOptions() item=__fieldNestedOption}
1315
<option
1416
value="{$__fieldNestedOption[value]}"

wcfsetup/install/files/lib/system/form/builder/field/SelectFormField.class.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ final class SelectFormField extends AbstractFormField implements
3636
*/
3737
private bool $ignoreInvalidValues = false;
3838

39+
/**
40+
* @since 6.2
41+
*/
42+
private ?string $defaultValue = null;
43+
3944
/**
4045
* @inheritDoc
4146
*/
@@ -102,4 +107,43 @@ public function ignoreInvalidValues(bool $ignoreInvalidValues = true): self
102107

103108
return $this;
104109
}
110+
111+
/**
112+
* Sets an initial default value.
113+
*
114+
* The provided value must be among the existing values, setting it to
115+
* `null` disables this feature. When a default value is present the default
116+
* option “No Selection” becomes unavailable.
117+
*
118+
* @since 6.2
119+
*/
120+
public function defaultValue(?string $defaultValue = null): self
121+
{
122+
if ($defaultValue !== null && !isset($this->getOptions()[$defaultValue])) {
123+
throw new \InvalidArgumentException("Unknown default value '{$defaultValue}' for field '{$this->getId()}'.");
124+
}
125+
126+
$this->defaultValue = $defaultValue;
127+
128+
return $this;
129+
}
130+
131+
/**
132+
* @since 6.2
133+
*/
134+
public function hasDefaultValue(): bool
135+
{
136+
return $this->defaultValue !== null;
137+
}
138+
139+
#[\Override]
140+
public function getValue()
141+
{
142+
$value = parent::getValue();
143+
if ($value === null && $this->defaultValue !== null) {
144+
return $this->defaultValue;
145+
}
146+
147+
return $value;
148+
}
105149
}

0 commit comments

Comments
 (0)