Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion com.woltlab.wcf/templates/shared_selectFormField.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
required
{/if}
>
<option value="">{lang}wcf.global.noSelection{/lang}</option>
{if !$field->hasDefaultValue()}
<option value="">{lang}wcf.global.noSelection{/lang}</option>
{/if}
{foreach from=$field->getNestedOptions() item=__fieldNestedOption}
<option
value="{$__fieldNestedOption[value]}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ final class SelectFormField extends AbstractFormField implements
*/
private bool $ignoreInvalidValues = false;

/**
* @since 6.2
*/
private ?string $defaultValue = null;

/**
* @inheritDoc
*/
Expand Down Expand Up @@ -102,4 +107,43 @@ public function ignoreInvalidValues(bool $ignoreInvalidValues = true): self

return $this;
}

/**
* Sets an initial default value.
*
* The provided value must be among the existing values, setting it to
* `null` disables this feature. When a default value is present the default
* option “No Selection” becomes unavailable.
*
* @since 6.2
*/
public function defaultValue(?string $defaultValue = null): self
{
if ($defaultValue !== null && !isset($this->getOptions()[$defaultValue])) {
throw new \InvalidArgumentException("Unknown default value '{$defaultValue}' for field '{$this->getId()}'.");
}

$this->defaultValue = $defaultValue;

return $this;
}

/**
* @since 6.2
*/
public function hasDefaultValue(): bool
{
return $this->defaultValue !== null;
}

#[\Override]
public function getValue()
{
$value = parent::getValue();
if ($value === null && $this->defaultValue !== null) {
return $this->defaultValue;
}

return $value;
}
}