Skip to content

Instantly share code, notes, and snippets.

@gunnarlium
Created May 16, 2015 08:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunnarlium/cde05222864902af94d9 to your computer and use it in GitHub Desktop.
Save gunnarlium/cde05222864902af94d9 to your computer and use it in GitHub Desktop.
Symfony/Silex data transformer, in reference to https://twitter.com/dragonmantank/status/599399796181487616
<?php
namespace App\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
class ArrayToStringTransformer implements DataTransformerInterface
{
public function transform($value)
{
if (!is_array($value)) {
return '';
}
return join(', ', $value);
}
public function reverseTransform($value)
{
return array_map('trim', explode(',', $value));
}
}
<?php
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use App\Form\DataTransformer\ArrayToStringTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;
class VideoType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'title',
'text',
array(
'attr' => array('class' => 'spans6'),
'constraints' => array(new Assert\NotBlank())
)
)
->add($builder
->create('tags', 'text', array('required' => false, 'attr' => array('class' => 'spans6')))
->addModelTransformer(new ArrayToStringTransformer())
);
}
public function getName()
{
return 'item';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment