0
votes

I clone an entity and after I persist a prePersist function is called to set the creating date and user , and when return the flush function gives an Undefined index for my entity I cloned

the clone function is :

public function cloneService($id)
{

    $manager = $this->container->get('doctrine')->getManager();
    $repository = $this->em->getRepository(Article::class);
    $article = $repository->find($id);

    $clonedObject = clone $article;
    $clonedObject->setTitle('[Duplicate]'.$article->getTitle());
    $clonedObject->setEnabled(false);

    $manager->persist($clonedObject);
    $manager->flush();


    return ;
}

and the prePersist is

public function prePersist(LifecycleEventArgs $args)
{
    if ($this->tokenStorage->getToken() === null ) {
        return ;
    }
    $user = $this->tokenStorage->getToken()->getUser();
    $object = $args->getEntity();


    if ($this->hasDateTimeTrait($object)) {
        $this->setCreated($user, $object);
        $this->setUpdated($user, $object);
    }
}

and the result is

DoctrineORMEntityManager_0000000041a2ac07000000000bca81cc14d7185c1fc2068ccb74c3ea035ec2eb->flush() in src/Exozet/AcademyBundle/Service/CloneService.php (line 45) $clonedObject->setEnabled(false); $manager->persist($clonedObject); $manager = $this->container->get('doctrine')->getManager(); $repository = $this->em->getRepository(Article::class); $manager->flush();

1
Where is line 45 ?Weenesta - Mathieu Dormeval
I think that $this->tokenStorage->getToken() is only available in Symfony Controller, not in Service.Weenesta - Mathieu Dormeval
@MathieuDormeval it is if you inject it, but isn't the prePersist function located in the entity ? You don't have the tokenStorage there, set the user from the cloneServiceJeroen

1 Answers

0
votes

Try with

...
$clonedObject = clone $article;
$clonedObject->setId(null);
...