Skip to content

[Form] Added "html5" option to both MoneyType and PercentType #35956

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 24, 2020
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions src/Symfony/Component/Form/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ CHANGELOG
* Added support for using the `{{ label }}` placeholder in constraint messages, which is replaced in the `ViolationMapper` by the corresponding field form label.
* Added `DataMapper`, `ChainAccessor`, `PropertyPathAccessor` and `CallbackAccessor` with new callable `getter` and `setter` options for each form type
* Deprecated `PropertyPathMapper` in favor of `DataMapper` and `PropertyPathAccessor`
* Added a `html5` option to `MoneyType` and `PercentType`, to use `<input type="number" />`

5.1.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransform
{
private $divisor;

public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, ?int $divisor = 1)
public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, ?int $divisor = 1, string $locale = null)
{
if (null === $grouping) {
$grouping = true;
Expand All @@ -33,7 +33,7 @@ public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $round
$scale = 2;
}

parent::__construct($scale, $grouping, $roundingMode);
parent::__construct($scale, $grouping, $roundingMode, $locale);

if (null === $divisor) {
$divisor = 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,19 @@ class PercentToLocalizedStringTransformer implements DataTransformerInterface
private $roundingMode;
private $type;
private $scale;
private $html5Format;

/**
* @see self::$types for a list of supported types
*
* @param int $scale The scale
* @param string $type One of the supported types
* @param int $scale The scale
* @param string $type One of the supported types
* @param int|null $roundingMode A value from \NumberFormatter, such as \NumberFormatter::ROUND_HALFUP
* @param bool $html5Format Use an HTML5 specific format, see https://www.w3.org/TR/html51/sec-forms.html#date-time-and-number-formats
*
* @throws UnexpectedTypeException if the given value of type is unknown
*/
public function __construct(int $scale = null, string $type = null, ?int $roundingMode = null)
public function __construct(int $scale = null, string $type = null, ?int $roundingMode = null, bool $html5Format = false)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I would rather allow passing a $locale and $grouping argument like in the NumberToLocalizedStringTransformer.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have missed feelings about that: HTML5 format happens to be en locale without grouping, but it's accidental. I feel like it is correct to expose clearly that we want HTML5-compatible format in the normalizer interface.

{
if (null === $scale) {
$scale = 0;
Expand All @@ -64,6 +67,7 @@ public function __construct(int $scale = null, string $type = null, ?int $roundi
$this->type = $type;
$this->scale = $scale;
$this->roundingMode = $roundingMode;
$this->html5Format = $html5Format;
}

/**
Expand Down Expand Up @@ -182,7 +186,13 @@ public function reverseTransform($value)
*/
protected function getNumberFormatter()
{
$formatter = new \NumberFormatter(\Locale::getDefault(), \NumberFormatter::DECIMAL);
// Values used in HTML5 number inputs should be formatted as in "1234.5", ie. 'en' format without grouping,
// according to https://www.w3.org/TR/html51/sec-forms.html#date-time-and-number-formats
$formatter = new \NumberFormatter($this->html5Format ? 'en' : \Locale::getDefault(), \NumberFormatter::DECIMAL);

if ($this->html5Format) {
$formatter->setAttribute(\NumberFormatter::GROUPING_USED, 0);
}

$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->scale);

Expand Down
21 changes: 20 additions & 1 deletion src/Symfony/Component/Form/Extension/Core/Type/MoneyType.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Form\Extension\Core\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Exception\LogicException;
use Symfony\Component\Form\Extension\Core\DataTransformer\MoneyToLocalizedStringTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
Expand All @@ -28,12 +29,15 @@ class MoneyType extends AbstractType
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Values used in HTML5 number inputs should be formatted as in "1234.5", ie. 'en' format without grouping,
// according to https://www.w3.org/TR/html51/sec-forms.html#date-time-and-number-formats
$builder
->addViewTransformer(new MoneyToLocalizedStringTransformer(
$options['scale'],
$options['grouping'],
$options['rounding_mode'],
$options['divisor']
$options['divisor'],
$options['html5'] ? 'en' : null
))
;
}
Expand All @@ -44,6 +48,10 @@ public function buildForm(FormBuilderInterface $builder, array $options)
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['money_pattern'] = self::getPattern($options['currency']);

if ($options['html5']) {
$view->vars['type'] = 'number';
}
}

/**
Expand All @@ -58,6 +66,7 @@ public function configureOptions(OptionsResolver $resolver)
'divisor' => 1,
'currency' => 'EUR',
'compound' => false,
'html5' => false,
'invalid_message' => function (Options $options, $previousValue) {
return ($options['legacy_error_messages'] ?? true)
? $previousValue
Expand All @@ -76,6 +85,16 @@ public function configureOptions(OptionsResolver $resolver)
]);

$resolver->setAllowedTypes('scale', 'int');

$resolver->setAllowedTypes('html5', 'bool');

$resolver->setNormalizer('grouping', function (Options $options, $value) {
if ($value && $options['html5']) {
throw new LogicException('Cannot use the "grouping" option when the "html5" option is enabled.');
}

return $value;
});
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
$options['scale'],
$options['type'],
$options['rounding_mode'],
false
$options['html5']
));
}

Expand All @@ -40,6 +40,10 @@ public function buildForm(FormBuilderInterface $builder, array $options)
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['symbol'] = $options['symbol'];

if ($options['html5']) {
$view->vars['type'] = 'number';
}
}

/**
Expand All @@ -57,6 +61,7 @@ public function configureOptions(OptionsResolver $resolver)
'symbol' => '%',
'type' => 'fractional',
'compound' => false,
'html5' => false,
'invalid_message' => function (Options $options, $previousValue) {
return ($options['legacy_error_messages'] ?? true)
? $previousValue
Expand Down Expand Up @@ -87,6 +92,7 @@ public function configureOptions(OptionsResolver $resolver)

return '';
});
$resolver->setAllowedTypes('html5', 'bool');
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -412,4 +412,84 @@ public function testReverseTransformDisallowsTrailingExtraCharactersMultibyte()

$transformer->reverseTransform("12\xc2\xa0345,678foo");
}

public function testTransformForHtml5Format()
{
$transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP, true);

// Since we test against "de_CH", we need the full implementation
IntlTestHelper::requireFullIntl($this, false);

\Locale::setDefault('de_CH');

$this->assertEquals('10', $transformer->transform(0.104));
$this->assertEquals('11', $transformer->transform(0.105));
$this->assertEquals('200000', $transformer->transform(2000));
}

public function testTransformForHtml5FormatWithInteger()
{
$transformer = new PercentToLocalizedStringTransformer(null, 'integer', \NumberFormatter::ROUND_HALFUP, true);

// Since we test against "de_CH", we need the full implementation
IntlTestHelper::requireFullIntl($this, false);

\Locale::setDefault('de_CH');

$this->assertEquals('0', $transformer->transform(0.1));
$this->assertEquals('1234', $transformer->transform(1234));
}

public function testTransformForHtml5FormatWithScale()
{
// Since we test against "de_CH", we need the full implementation
IntlTestHelper::requireFullIntl($this, false);

\Locale::setDefault('de_CH');

$transformer = new PercentToLocalizedStringTransformer(2, null, \NumberFormatter::ROUND_HALFUP, true);

$this->assertEquals('12.34', $transformer->transform(0.1234));
}

public function testReverseTransformForHtml5Format()
{
// Since we test against "de_CH", we need the full implementation
IntlTestHelper::requireFullIntl($this, false);

\Locale::setDefault('de_CH');

$transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP, true);

$this->assertEquals(0.02, $transformer->reverseTransform('1.5')); // rounded up, for 2 decimals
$this->assertEquals(0.15, $transformer->reverseTransform('15'));
$this->assertEquals(2000, $transformer->reverseTransform('200000'));
}

public function testReverseTransformForHtml5FormatWithInteger()
{
// Since we test against "de_CH", we need the full implementation
IntlTestHelper::requireFullIntl($this, false);

\Locale::setDefault('de_CH');

$transformer = new PercentToLocalizedStringTransformer(null, 'integer', \NumberFormatter::ROUND_HALFUP, true);

$this->assertEquals(10, $transformer->reverseTransform('10'));
$this->assertEquals(15, $transformer->reverseTransform('15'));
$this->assertEquals(12, $transformer->reverseTransform('12'));
$this->assertEquals(200, $transformer->reverseTransform('200'));
}

public function testReverseTransformForHtml5FormatWithScale()
{
// Since we test against "de_CH", we need the full implementation
IntlTestHelper::requireFullIntl($this, false);

\Locale::setDefault('de_CH');

$transformer = new PercentToLocalizedStringTransformer(2, null, \NumberFormatter::ROUND_HALFUP, true);

$this->assertEquals(0.1234, $transformer->reverseTransform('12.34'));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,18 @@ public function testDefaultFormattingWithSpecifiedRounding()

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

public function testHtml5EnablesSpecificFormatting()
{
// Since we test against "de_CH", we need the full implementation
IntlTestHelper::requireFullIntl($this, false);

\Locale::setDefault('de_CH');

$form = $this->factory->create(static::TESTED_TYPE, null, ['html5' => true, 'scale' => 2]);
$form->setData('12345.6');

$this->assertSame('12345.60', $form->createView()->vars['value']);
$this->assertSame('number', $form->createView()->vars['type']);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,34 @@
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
use Symfony\Component\Form\Extension\Core\Type\PercentType;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Intl\Util\IntlTestHelper;

class PercentTypeTest extends TypeTestCase
{
use ExpectDeprecationTrait;

const TESTED_TYPE = PercentType::class;

private $defaultLocale;

protected function setUp(): void
{
// we test against different locales, so we need the full
// implementation
IntlTestHelper::requireFullIntl($this, false);

parent::setUp();

$this->defaultLocale = \Locale::getDefault();
}

protected function tearDown(): void
{
parent::tearDown();

\Locale::setDefault($this->defaultLocale);
}

public function testSubmitWithRoundingMode()
{
$form = $this->factory->create(self::TESTED_TYPE, null, [
Expand All @@ -33,6 +54,35 @@ public function testSubmitWithRoundingMode()
$this->assertEquals(0.0124, $form->getData());
}

public function testSubmitNullUsesDefaultEmptyData($emptyData = '10', $expectedData = 0.1)
{
$form = $this->factory->create(static::TESTED_TYPE, null, [
'empty_data' => $emptyData,
'rounding_mode' => \NumberFormatter::ROUND_UP,
]);
$form->submit(null);

$this->assertSame($emptyData, $form->getViewData());
$this->assertSame($expectedData, $form->getNormData());
$this->assertSame($expectedData, $form->getData());
}

public function testHtml5EnablesSpecificFormatting()
{
\Locale::setDefault('de_CH');

$form = $this->factory->create(static::TESTED_TYPE, null, [
'html5' => true,
'rounding_mode' => \NumberFormatter::ROUND_UP,
'scale' => 2,
'type' => 'integer',
]);
$form->setData('1234.56');

$this->assertSame('1234.56', $form->createView()->vars['value']);
$this->assertSame('number', $form->createView()->vars['type']);
}

/**
* @group legacy
*/
Expand Down