Skip to content

Commit

Permalink
bug #32125 [Form] accept floats for input="string" in NumberType (xab…
Browse files Browse the repository at this point in the history
…buh)

This PR was merged into the 4.3 branch.

Discussion
----------

[Form] accept floats for input="string" in NumberType

| Q             | A
| ------------- | ---
| Branch?       | 4.3
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #31905, #32124
| License       | MIT
| Doc PR        |

Commits
-------

2abf855 accept floats for input="string" in NumberType
  • Loading branch information
fabpot committed Jun 22, 2019
2 parents 04b2f7f + 2abf855 commit 0dbf477
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Symfony/Component/Form/Extension/Core/Type/NumberType.php
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Form\Extension\Core\Type;

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

if ('string' === $options['input']) {
$builder->addModelTransformer(new StringToFloatTransformer($options['scale']));
$builder->addModelTransformer(new CallbackTransformer(
function ($value) {
return \is_float($value) || \is_int($value) ? (string) $value : $value;
},
function ($value) {
return $value;
}
));
}
}

Expand Down
Expand Up @@ -77,6 +77,26 @@ public function testDefaultFormattingWithScaleAndStringInput(): void
$this->assertSame('12345,68', $form->createView()->vars['value']);
}

public function testStringInputWithFloatData(): void
{
$form = $this->factory->create(static::TESTED_TYPE, 12345.6789, [
'input' => 'string',
'scale' => 2,
]);

$this->assertSame('12345,68', $form->createView()->vars['value']);
}

public function testStringInputWithIntData(): void
{
$form = $this->factory->create(static::TESTED_TYPE, 12345, [
'input' => 'string',
'scale' => 2,
]);

$this->assertSame('12345,00', $form->createView()->vars['value']);
}

public function testDefaultFormattingWithRounding(): void
{
$form = $this->factory->create(static::TESTED_TYPE, null, ['scale' => 0, 'rounding_mode' => \NumberFormatter::ROUND_UP]);
Expand Down

0 comments on commit 0dbf477

Please sign in to comment.