diff --git a/src/Forms/Controls/TextBase.php b/src/Forms/Controls/TextBase.php index 175a8ac74..e07f54736 100644 --- a/src/Forms/Controls/TextBase.php +++ b/src/Forms/Controls/TextBase.php @@ -11,6 +11,7 @@ use Nette; use Nette\Forms\Form; +use Nette\Forms\ScalarValue; use Nette\Utils\Strings; @@ -41,7 +42,7 @@ public function setValue($value) } elseif (!is_scalar($value) && !method_exists($value, '__toString')) { throw new Nette\InvalidArgumentException(sprintf("Value must be scalar or null, %s given in field '%s'.", gettype($value), $this->name)); } - $this->value = $value; + $this->value = $value instanceof ScalarValue ? $value->getMixedValue() : $value; $this->rawValue = (string) $value; return $this; } diff --git a/src/Forms/ScalarValue.php b/src/Forms/ScalarValue.php new file mode 100644 index 000000000..57c1e0869 --- /dev/null +++ b/src/Forms/ScalarValue.php @@ -0,0 +1,43 @@ +scalarValue = $scalarValue; + $this->mixedValue = $mixedValue; + } + + + /** + * @return mixed + */ + public function getMixedValue() + { + return $this->mixedValue; + } + + + public function __toString(): string + { + return $this->scalarValue; + } +} diff --git a/tests/Forms/Controls.BaseControl.phpt b/tests/Forms/Controls.BaseControl.phpt index e6b5b850b..4cef88fd0 100644 --- a/tests/Forms/Controls.BaseControl.phpt +++ b/tests/Forms/Controls.BaseControl.phpt @@ -7,6 +7,7 @@ declare(strict_types=1); use Nette\Forms\Form; +use Nette\Forms\ScalarValue; use Nette\Forms\Validator; use Tester\Assert; @@ -145,3 +146,30 @@ test(function () { // disabled & submitted Assert::same('default', $input->getValue()); }); + + +test(function () { // scalarValue + $form = new Form; + $input = $form->addText('text'); + $input->setValue(new ScalarValue('scalarValue', null)); + + Assert::null($input->getValue()); + Assert::same('', (string) $input->getControl()); +}); + + +test(function () { // scalarValue from filter + $form = new Form; + + $input = $form->addText('text'); + $input->setValue('scalarValue'); + $input->addFilter(function (string $scalarValue): ScalarValue { + return new ScalarValue($scalarValue, 'mixedValue'); + }); + + $form->validate(); + + Assert::same('mixedValue', $input->getValue()); + Assert::same('', (string) $input->getControl()); + Assert::true(Validator::validateFilled($input)); +});