Skip to content

Commit

Permalink
Add empty string support in Number field (#358)
Browse files Browse the repository at this point in the history
  • Loading branch information
vjik authored Jul 29, 2024
1 parent 7b5c866 commit 64b19c4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/Field/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,8 @@ protected function generateInput(): string
{
$value = $this->getValue();

if (!is_numeric($value) && $value !== null) {
throw new InvalidArgumentException('Number field requires a numeric or null value.');
if (!is_numeric($value) && $value !== '' && $value !== null) {
throw new InvalidArgumentException('Number field requires a numeric, an empty string or null value.');
}

/** @psalm-suppress MixedArgument We guess that enrichment contain correct values. */
Expand Down
32 changes: 31 additions & 1 deletion tests/Field/NumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -355,12 +355,42 @@ public function testTabIndex(): void
$this->assertSame($expected, $result);
}

public static function dataValues(): array
{
return [
[null, null],
[' value', ''],
[' value="0"', 0],
[' value="0.5"', 0.5],
[' value="1"', 1],
[' value="42"', '42'],
[' value="0.5"', '0.5'],
];
}

#[DataProvider('dataValues')]
public function testValues(?string $expected, mixed $value): void
{
$result = Number::widget()
->name('test')
->value($value)
->render();

$expectedHtml = <<<HTML
<div>
<input type="number" name="test"$expected>
</div>
HTML;

$this->assertSame($expectedHtml, $result);
}

public function testInvalidValue(): void
{
$field = Number::widget()->value('hello');

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Number field requires a numeric or null value.');
$this->expectExceptionMessage('Number field requires a numeric, an empty string or null value.');
$field->render();
}

Expand Down

0 comments on commit 64b19c4

Please sign in to comment.