Skip to content

Instantly share code, notes, and snippets.

@leftdevel
Last active August 29, 2015 14:22
Show Gist options
  • Save leftdevel/7c482c13ecaadf59d213 to your computer and use it in GitHub Desktop.
Save leftdevel/7c482c13ecaadf59d213 to your computer and use it in GitHub Desktop.
<?php
namespace LeftDevel\Form\Transformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class MultiOrderTransformer implements DataTransformerInterface
{
public function transform($length)
{
if (!$length) {
return [
'feet' => 0,
'inches' => 0,
];
}
return [
'feet' => intval($length / 12),
'inches' => $length % 12,
];
}
public function reverseTransform($parts)
{
if (!is_array($parts)) {
throw new TransformationFailedException('Expected array');
}
if (!(isset($parts['feet']) && isset($parts['inches']))) {
throw new TransformationFailedException('Feet and Inches must be defined');
}
return $parts['feet'] * 12 + $parts['inches'];
}
}
<?php
namespace LeftDevel\Form\Type;
use Symfony\Component\OptionsResolver\OptionsResolverInterface,
Symfony\Component\Form\AbstractType,
Symfony\Component\Form\FormBuilderInterface;
use LeftDevel\Form\Transformer\MultiOrderTransformer;
class MultiOrderType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->addViewTransformer(new MultiOrderTransformer())
->add('feet', 'text')
->add('inches', 'text')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array('compound' => true));
}
public function getName()
{
return 'multi_order_type';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment