2015-12-02 139 views
0

我在表单提交时使用事件侦听器,其中,我需要捕获一个xml文件,打开它并提取其内容,将它放在一个实体上,并将其添加到一个集合中其他实体。Symfony2上的数组集合持久性

目前这个作品:

$builder->addEventListener(FormEvents::SUBMIT, function(FormEvent $event){ 
     $entity = $event->getData(); 
     if($entity){ 
      $parent = $event->getForm()->getParent()->getData(); 
      $gpx = $entity['gpx']; 
      if($gpx){ 
       $xmlGpx = simplexml_load_file($gpx); 
       foreach ($xmlGpx->wpt as $pt) { 
        $point = new MonitoringPoint(); 
        $point->setPoint(new \CrEOF\Spatial\PHP\Types\Geometry\Point((string) $pt['lat'], (string) $pt['lon'])); 
        $point->setAltitude((float) $pt->ele); 
        $point->setDate(($pt->time->count() ? new \DateTime((string)$pt->time) : null)); 
        $point->setAccuracy((float) $pt->hdop); 
        $parent->addMonitoringPoint($point); 
       } 

       $fileName = $gpx->getClientOriginalName(); 
       $directory = __DIR__.'/../../../../web/uploads/'; 
       $date = new \DateTime(); 

       $newFileName = md5($gpx->getClientOriginalName().$date->getTimestamp()); 
       $gpx->move($directory, $fileName); 
       $fs = new Filesystem(); 
       $fs->rename($directory.$fileName, $directory.$newFileName.'.gpx'); 
       $parent->setGpx($newFileName.'.gpx'); 

      } 
     } 
    }); 

$parentMonitoring的情况下,如果我打开$parent我会看到$point瓦尔已对变量的集合monitoringPoints,并将GPX太。

但后来我去故见右前已经持续,里​​面newAction

$entity = new Monitoring($params); 

    $form = $this->createForm(new MonitoringType(), $entity, array(
     'action' => $this->generateUrl('my_route'), 
     'method' => 'POST', 
    )); 

    $form->handleRequest($request); 

    if ($form->isSubmitted() && $form->isValid()) { 
     dump($entity);die; 
     $em = $this->getDoctrine()->getManager(); 
     $em->persist($entity); 
     $em->flush(); 
    } 

和集合为空实体!但gpx属性包含正确的值。 集合是否被重置?

+0

请务必阅读并理解http://doctrine-orm.readthedocs.org/projects/doctrine-orm/ EN /最新/reference/unitofwork-associations.html - 我很确定这是你的问题。 – LBA

回答

0

我不得不在传递点到会话中的数组,仍然认为这是不是最好的选择,但在newAction工作

$array = []; 
foreach ($xmlGpx->wpt as $pt) { 
    $point = new MonitoringPoint(); 
    $point->setPoint(new \CrEOF\Spatial\PHP\Types\Geometry\Point((string) $pt['lat'], (string) $pt['lon'])); 
    $point->setAltitude((float) $pt->ele); 
    $point->setDate(($pt->time->count() ? new \DateTime((string)$pt->time) : null)); 
    $point->setAccuracy((float) $pt->hdop); 
    $point->setMonitoring($parent); 
    array_push($array, $point); 
} 
$session = new Session(); 
$session->getFlashBag()->add('array', $array); 

$em = $this->getDoctrine()->getManager(); 
$session = new Session(); 
$array = $session->getFlashBag()->get('array'); 
foreach($array[0] as $point) { 
    $point->setMonitoring($entity); 
    $entity->addMonitoringPoint($point); 
} 

$em->persist($entity); 
$em->flush(); 

不知道为什么阵列在控制器中被重新设置,因为我在提交过程中设置了实体中的点数