EntityToIDTransformer.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\BaseApplicationBundle\Form\ValueTransformer;
  11. use Symfony\Component\Form\ValueTransformer\ValueTransformerInterface;
  12. use Symfony\Component\Form\ValueTransformer\TransformationFailedException;
  13. use Symfony\Component\Form\Configurable;
  14. /**
  15. * Transforms a Doctrine Entity into its identifier value and back.
  16. *
  17. * This only works with single-field primary key fields.
  18. *
  19. * @author Benjamin Eberlei <kontakt@beberlei.de>
  20. */
  21. class EntityToIDTransformer extends Configurable implements ValueTransformerInterface
  22. {
  23. protected function configure()
  24. {
  25. $this->addRequiredOption('em');
  26. $this->addRequiredOption('className');
  27. parent::configure();
  28. }
  29. /**
  30. * Reverse Transforming the selected id value to an Doctrine Entity.
  31. *
  32. * This handles NULL, the EntityManager#find method returns null if no entity was found.
  33. *
  34. * @param int|string $newId
  35. * @param object $oldEntity
  36. * @return object
  37. */
  38. public function reverseTransform($newId)
  39. {
  40. if (empty($newId)) {
  41. return null;
  42. }
  43. return $this->getOption('em')->find($this->getOption('className'), $newId);
  44. }
  45. /**
  46. * @param object $entity
  47. * @return int|string
  48. */
  49. public function transform($entity)
  50. {
  51. if (empty($entity)) {
  52. return 0;
  53. }
  54. return current( $this->getOption('em')->getUnitOfWork()->getEntityIdentifier($entity) );
  55. }
  56. }