Skip to content

Instantly share code, notes, and snippets.

@craigmarvelley
Forked from bjo3rnf/EntityHiddenType.php
Created February 11, 2013 16:53
Show Gist options
  • Save craigmarvelley/4755684 to your computer and use it in GitHub Desktop.
Save craigmarvelley/4755684 to your computer and use it in GitHub Desktop.
<?php
namespace Dpn\ToolsBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Dpn\ToolsBundle\Form\DataTransformer\EntityToIdTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\Common\Persistence\ObjectManager;
class EntityHiddenType extends AbstractType
{
/**
* @var ObjectManager
*/
protected $objectManager;
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new EntityToIdTransformer($this->objectManager, $options['class']);
$builder->addModelTransformer($transformer);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'class' => null,
'invalid_message' => 'The entity does not exist.',
));
}
public function getParent()
{
return 'hidden';
}
public function getName()
{
return 'entity_hidden';
}
}
<?php
namespace Dpn\ToolsBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;
class EntityToIdTransformer implements DataTransformerInterface
{
/**
* @var ObjectManager
*/
protected $objectManager;
/**
* @var string
*/
protected $class;
public function __construct(ObjectManager $objectManager, $class)
{
$this->objectManager = $objectManager;
$this->class = $class;
}
public function transform($entity)
{
if (null === $entity) {
return;
}
return $entity->getId();
}
public function reverseTransform($id)
{
if (!$id) {
return null;
}
$entity = $this->objectManager
->getRepository($this->class)
->find($id);
if (null === $entity) {
throw new TransformationFailedException();
}
return $entity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment