Skip to content

[Form] MoneyType: allow "string" as input #59710

Closed
@jmsche

Description

@jmsche

Description

I use the MoneyType with the scale option set to 4.

The property is a string, using the decimal Doctrine type. And the setter on the entity accepts a string as argument.

When submitting the form & saving the entity into the database, there's always an update of the entity, even if the value has not changed (it's rounding e.g. 0.0000 to 0).

I noticed the issue disappears if I use the same form configuration, but using the NumberType instead, with the input option set to string. However, the input option of the MoneyType does not accept the string value.

I currently fixed the issue with a form extension:

<?php

declare(strict_types=1);

namespace App\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\DataTransformer\StringToFloatTransformer;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\FormBuilderInterface;

final class MoneyTypeExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->addModelTransformer(new StringToFloatTransformer($options['scale']));
    }

    public static function getExtendedTypes(): iterable
    {
        return [MoneyType::class];
    }
}

But I think it would be better to allow string for the input option like the NumberType does?

Example

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions