-
-
Save brpaz/5957acfd5d0e88548287 to your computer and use it in GitHub Desktop.
Data Transformer: Many to Many for Entity Field #symfony #datatransformer
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 Doctrine\ORM\EntityManager; | |
use Doctrine\ORM\PersistentCollection; | |
use Doctrine\Common\Collections\ArrayCollection; | |
use Symfony\Component\Form\DataTransformerInterface; | |
use Symfony\Component\Form\Exception\TransformationFailedException; | |
class ManyToEntityTransformer implements DataTransformerInterface | |
{ | |
/** | |
* @var EntityManager | |
*/ | |
private $em; | |
/** | |
* @var string | |
*/ | |
private $class; | |
/** | |
* @param EntityManager $em | |
*/ | |
public function __construct(EntityManager $em, $class) | |
{ | |
$this->em = $em; | |
$this->class = $class; | |
} | |
/** | |
* Transforms an object (use) to a string (id). | |
* | |
* @param array $array | |
* @return ArrayCollection | |
*/ | |
public function transform($array) | |
{ | |
$newArray = array(); | |
if (!($array instanceof PersistentCollection)) { | |
return new ArrayCollection(); | |
} | |
foreach ($array as $key => $value) { | |
$newArray[] = $value; | |
} | |
return new ArrayCollection($newArray); | |
} | |
/** | |
* Transforms a string (id) to an object (item). | |
* | |
* @param string $id | |
* @return PersistentCollection|ArrayCollection | |
*/ | |
public function reverseTransform($array) | |
{ | |
$newArray = array(); | |
if (!$array) { | |
return new ArrayCollection(); | |
} | |
foreach ($array as $key => $value) { | |
$item = $this->em | |
->getRepository($this->class) | |
->findOneBy(array('id' => $value)) | |
; | |
if (!is_null($item)) { | |
$newArray[$key] = $item; | |
} | |
} | |
return new PersistentCollection($this->em, $this->class, new ArrayCollection($newArray)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment