Created
December 4, 2013 18:17
-
-
Save dantoncancella/7792621 to your computer and use it in GitHub Desktop.
Entity Hidden Type Symfony 2
This file contains hidden or 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 Acme\DemoBundle\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; | |
} | |
} |
This file contains hidden or 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: | |
acme_demo.type.entity_hidden: | |
class: Acme\DemoBundle\Form\Type\EntityHiddenType | |
arguments: ["@doctrine.orm.entity_manager"] | |
tags: | |
- { name: form.type, alias: entity_hidden } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment