Last active
November 19, 2021 17:19
-
-
Save bjo3rnf/4061232 to your computer and use it in GitHub Desktop.
Hidden field for Symfony2 entities
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; | |
} | |
} |
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://gist.github.com/xanou/e630e4e25df60d33b050 )
Thanks, you made my day!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.