Search code examples
phpsymfonynumbersdecimallocale

symfony2: how to use points instead of comma for decimals separator while keeping fr locale


In Symfony 2, with a french default locale, there are some cases when decimal values separator are rendered as commas in forms.

Commas in forms are not always converted to points which is the separator used by my database.

How can I make sure every numeric data field comma is replaced by a point after form sumission?

I found the NumberToLocalizedStringTransformer:

This reference but do I need to add a datatransformer to every form to make it work as I wish ?


Solution

  • Using a DataTransformer is one approach to solving your localization problem. You don't need to add it to every form. You can create your own FormType extending or inheriting the (I guess) number type. Within your own form type add the transformer with a call to FormBuilderInterface::addViewTranformer().

    You can find more information here. Here is an example from one of my own custom types. Using this method you are also able to customize the widget used for rendering.

    class CustomType extends NumberType
    {        
        public function buildForm ( FormBuilderInterface $builder, array $options )
        {
            parent::buildForm( $builder, $options );
    
            $builder->addViewTransformer( new CustomTransformer() );
        }
    
        public function getName()
        {
            return 'my_custom_type';
        }
    }
    

    Then when you want to use your localized numbers build your form with a my_custom_type instead of number.

    Another solution would be to force your users to use points by showing an error if they use anything else. Look here for Symfony form validation. The Regex validator with something like /^(\d|\.)+$/ would work.