Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Improve number field: allow empty/null, add defaultValue #2886

Merged
merged 3 commits into from
May 15, 2018
Merged
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
21 changes: 17 additions & 4 deletions src/fields/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ public static function displayName(): string
// Properties
// =========================================================================

/**
* @var int|float|null The default value for new elements
*/
public $defaultValue;

/**
* @var int|float The minimum allowed number
*/
Expand Down Expand Up @@ -67,6 +72,11 @@ public function init()
{
parent::init();

// Normalize $defaultValue
if ($this->defaultValue === '') {
$this->defaultValue = null;
}

// Normalize $max
if ($this->max !== null && empty($this->max)) {
$this->max = null;
Expand Down Expand Up @@ -134,20 +144,23 @@ public function normalizeValue($value, ElementInterface $element = null)
$value = Localization::normalizeNumber($value['value'], $value['locale']);
}

return $value;
return $this->isValueEmpty($value, $element) ? null : $value;
}

/**
* @inheritdoc
*/
public function getInputHtml($value, ElementInterface $element = null): string
{
$decimals = $this->decimals;
if ($this->isFresh($element) && $this->defaultValue !== null) {
$value = $this->defaultValue;
}


// If decimals is 0 (or null, empty for whatever reason), don't run this
if ($decimals) {
if ($value !== null && $this->decimals) {
$decimalSeparator = Craft::$app->getLocale()->getNumberSymbol(Locale::SYMBOL_DECIMAL_SEPARATOR);
$value = number_format($value, $decimals, $decimalSeparator, '');
$value = number_format($value, $this->decimals, $decimalSeparator, '');
}

return '<input type="hidden" name="'.$this->handle.'[locale]" value="'.Craft::$app->language.'">'.
Expand Down