Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.