简体   繁体   中英

Assigning cloned object in SonataAdmin class

I want to create Game object with cloned Scenario object.

Create Game form:
    Name: My game
    Scenario: MyScenario (Combo box)

Basing on answer for Deep clone Doctrine entity with related entities question I have implemented __clone methods.

I'm using __clone method in prePersist method in GameAdmin class.

public function prePersist($game)
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    $game->setAuthor($user);
    $cp = clone $game->getScenario(); //Error after add this
    $game->setScenario($cp);          //two lines
}

I'm not sure is this a proper place for doing this operation because I'm getting MappingException :

The class 'Doctrine\ORM\Persisters\ManyToManyPersister' was not found in the chain 
configured namespaces Sonata\MediaBundle\Entity, FOS\UserBundle\Entity, 
Sonata\UserBundle\Entity, Application\Sonata\MediaBundle\Entity, 
Application\Sonata\UserBundle\Entity, GM\AppBundle\Entity

In Scenario entity I have $tasks which is ArrayCollection . I was cloning entire collection and that cause problems.

Cloning each task in loop solves problem:

public function __clone()
{
    if($this->id)
    {
        $this->setId(null);
        $ta = new ArrayCollection();
        foreach($this->tasks as $task)
        {
            $ta[] = clone $task;
        }
        $this->tasks = $ta;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM