2012-01-16 41 views
0

有關的symfony 2.保存數據快速的問題我有這樣的方法(只是用於測試):symfony的2保存數據

protected function createProduct() 
{ 
    $product = new Product(); 
    $product->setName('My product'); 
    $product->setDescription('Lorem ipsum dolor sit amet'); 
    $product->setIsPublished(1); 
    $product->setPosition(1); 


    $em = $this->getDoctrine()->getEntityManager(); 
    $em->persist($product); 
    $em->flush(); 
} 

然後,我有行動(只是用於測試也):

public function indexAction() 
{ 
    $this->createCategory(); 
    ... 
    render ... 
} 

我的問題是,當我執行索引操作時,產品在我的數據庫中保存兩次。有沒有人有類似的問題?任何方式來解決它?

更新: - 全面控制測試類:

namespace Test\CategoryBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Test\CategoryBundle\Entity\Category; 
use Symfony\Component\HttpFoundation\Response; 

class CategoryController extends Controller 
{ 
    public function createAction() 
    { 
     $c = new Category(); 
     $c->setName('Category'); 
     $c->setDescription('Lorem ipsum dolor sit amet'); 
     $c->setIsPublished(1); 
     $c->setPosition(1); 


     $em = $this->getDoctrine()->getEntityManager(); 
     $em->persist($c); 
     $em->flush(); 

     return new Response('Created category id '.$c->getId()); 

    } 

} 

路由放在src /測試/ CategoryBundle /資源/配置/ routing.yml中:

TestCategoryBundle_create: 
    pattern: /category/create 
    defaults: { _controller: TestCategoryBundle:Category:create } 

路由在app /配置/路由。 yml:

TestCategoryBundle: 
    resource: "@TestCategoryBundle/Resources/config/routing.yml" 
    prefix: /
+1

您發佈的代碼不應該以這種方式表現。這個問題應該在這個代碼之外。也許你的'createProduct'在其他地方調用,或者'indexAction'被調用兩次? – J0HN 2012-01-17 08:24:58

+0

我正在尋找重複,但我沒有它。這是控制器中唯一的方法。無論如何,如果我使用燈具束,數據插入正確。這是我的完整控制器類: – radri 2012-01-17 10:50:39

+0

這是您運行該頁面兩次的結果嗎?控制器看起來應該只向數據庫添加一個實體。 – 2012-01-18 02:13:33

回答

2

我發現了這個問題。我還不知道這是否正常,但至少數據不會重複。

該問題已通過向createAction方法添加重定向來解決。如果您未使用重定向,則數據將被複制。這是正常的 ???無論如何,這是爲我工作的解決方案。

public function createAction() 
{ 
    $c = new Category(); 
    $c->setName('My Category'); 
    $c->setDescription('Lorem ipsum dolor sit amet'); 
    $c->setIsPublished(1); 
    $c->setPosition(1); 

    $em = $this->getDoctrine()->getEntityManager(); 
    $em->persist($c); 
    $em->flush(); 

    return $this->redirect($this->generateUrl('your_routing_name_to_redirect')); 
} 
+0

不幸的是,這不是我的解決方案。我有同樣的問題,找不到原因。我在一個簡單的控制器上嘗試了這一點,並寫入錯誤記錄。訪問頁面後,我有兩個日誌條目,但分析器只顯示一個條目。但事實上它是兩個 – 2012-11-04 19:32:09

+0

我不知道WTF,但是這個錯誤只在我的機器上(Mac OS)和開發服務器上(unix)沒有問題 – 2012-11-04 19:55:35

0

我在Symfony 1.4中有類似的問題。

我發現了一個

<img src=""> 

(無SRC atributte),它使頁面加載自身。它不是一個symfony問題,它的瀏覽器功能:P

也許你也有一個。