Skip to content

Instantly share code, notes, and snippets.

@chrif
Forked from fain182/gist:3394880
Created August 21, 2012 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrif/3411067 to your computer and use it in GitHub Desktop.
Save chrif/3411067 to your computer and use it in GitHub Desktop.
Workaround for Issue #2059 in Symfony 2.0
<?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;
}
}
<?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';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment