public
Created — forked from fain182/gist:3394880

Workaround for Issue #2059 in Symfony 2.0

  • Download Gist
NumberToStringTransformer.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
<?php
namespace Acme\HelloBundle\Form\DataTransformer;
 
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Exception\TransformationFailedException;
 
/**
* A simple number transformer that allows either comma or dot as decimal separator.
*
* Caution: this transformer does not understand thousands separators.
*
* @see https://github.com/symfony/symfony/pull/2119
* @see https://github.com/symfony/symfony/issues/2059
* @see http://stackoverflow.com/questions/12026050/how-to-create-a-number-field-that-accepts-numbers-with-comma-or-period-in-symfon
*
*/
class NumberToStringTransformer implements DataTransformerInterface
{
/**
* @param mixed $value
* @return string
* @throws \Symfony\Component\Form\Exception\UnexpectedTypeException
*/
public function transform($value)
{
if (null === $value) {
return '';
}
 
if (!is_numeric($value)) {
throw new UnexpectedTypeException($value, 'numeric');
}
 
return (string)$value;
}
 
/**
* @param mixed $value
* @return float|mixed|null
* @throws \Symfony\Component\Form\Exception\UnexpectedTypeException
* @throws \Symfony\Component\Form\Exception\TransformationFailedException
*/
public function reverseTransform($value)
{
if (!is_string($value)) {
throw new UnexpectedTypeException($value, 'string');
}
 
if ('' === $value) {
return null;
}
 
$value = str_replace(',', '.', $value);
 
if (is_numeric($value)) {
$value = (float)$value;
} else {
throw new TransformationFailedException('not a number');
}
 
return $value;
}
}
NumberType.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
<?php
namespace Acme\HelloBundle\Form;
 
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
 
/**
*
*/
class NumberType extends AbstractType
{
/**
* @param \Symfony\Component\Form\FormBuilder $builder
* @param array $options
*/
public function buildForm(FormBuilder $builder, array $options)
{
$builder->appendClientTransformer(new DataTransformer\NumberToStringTransformer());
}
 
/**
* @param array $options
* @return string
*/
public function getParent(array $options)
{
return 'field';
}
 
/**
* @return string
*/
public function getName()
{
return 'calculator_number';
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.