2015-12-02 93 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(); 

不知道爲什麼陣列在控制器中被重新設置,因爲我在提交過程中設置了實體中的點數