Last active
December 21, 2016 16:39
-
-
Save simshaun/f79ddd19891148027e64349410062bf4 to your computer and use it in GitHub Desktop.
Hidden EntityType field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
form.type.entity_hidden: | |
class: PlatformBundle\Form\Type\EntityHiddenType | |
arguments: | |
- '@doctrine.orm.entity_manager' | |
tags: | |
- { name: form.type } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace PlatformBundle\Form\DataTransformer; | |
use Doctrine\Common\Persistence\ObjectManager; | |
use Symfony\Component\Form\DataTransformerInterface; | |
use Symfony\Component\Form\Exception\TransformationFailedException; | |
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 null; | |
} | |
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