Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
->setRequired(array('class'))
->setDefaults(array(
'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
You can’t perform that action at this time.