Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9b5ec43

Browse files
committed
accepts floats for input="string" in NumberType
1 parent 030396a commit 9b5ec43

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Symfony/Component/Form/Extension/Core/Type/NumberType.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
namespace Symfony\Component\Form\Extension\Core\Type;
1313

1414
use Symfony\Component\Form\AbstractType;
15+
use Symfony\Component\Form\CallbackTransformer;
1516
use Symfony\Component\Form\Exception\LogicException;
1617
use Symfony\Component\Form\Extension\Core\DataTransformer\NumberToLocalizedStringTransformer;
1718
use Symfony\Component\Form\Extension\Core\DataTransformer\StringToFloatTransformer;
@@ -37,6 +38,14 @@ public function buildForm(FormBuilderInterface $builder, array $options)
3738

3839
if ('string' === $options['input']) {
3940
$builder->addModelTransformer(new StringToFloatTransformer($options['scale']));
41+
$builder->addModelTransformer(new CallbackTransformer(
42+
function ($value) {
43+
return \is_float($value) || \is_int($value) ? (string) $value : $value;
44+
},
45+
function ($value) {
46+
return $value;
47+
}
48+
));
4049
}
4150
}
4251

src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,26 @@ public function testDefaultFormattingWithScaleAndStringInput(): void
7777
$this->assertSame('12345,68', $form->createView()->vars['value']);
7878
}
7979

80+
public function testStringInputWithFloatData(): void
81+
{
82+
$form = $this->factory->create(static::TESTED_TYPE, 12345.6789, [
83+
'input' => 'string',
84+
'scale' => 2,
85+
]);
86+
87+
$this->assertSame('12345,68', $form->createView()->vars['value']);
88+
}
89+
90+
public function testStringInputWithIntData(): void
91+
{
92+
$form = $this->factory->create(static::TESTED_TYPE, 12345, [
93+
'input' => 'string',
94+
'scale' => 2,
95+
]);
96+
97+
$this->assertSame('12345,00', $form->createView()->vars['value']);
98+
}
99+
80100
public function testDefaultFormattingWithRounding(): void
81101
{
82102
$form = $this->factory->create(static::TESTED_TYPE, null, ['scale' => 0, 'rounding_mode' => \NumberFormatter::ROUND_UP]);

0 commit comments

Comments
 (0)