Forked from lars-feyerabend/EntityHiddenType.php
Last active
August 29, 2015 14:22
-
-
Save hanicker/6cb5b8ad023664894ca3 to your computer and use it in GitHub Desktop.
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 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; | |
| } | |
| } |
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
| hidden_entity_form_type: | |
| class: \Acme\DemoBundle\Form\Type\HiddenEntityType | |
| arguments: | |
| - @doctrine.orm.entity_manager | |
| tags: | |
| - { name: form.type, alias: entity_hidden } |
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 | |
| // ... | |
| $form = $this->createFormBuilder(array('user' => $user)) | |
| ->add('user', 'hidden_entity', array( | |
| 'class' => '\Acme\DemoBundle\Entity\User' | |
| )) | |
| ->getForm() | |
| ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment