2015-04-26 61 views
2

我想建立Symfony2的REST API,但我與FOSRestBundleFOSRestBundle形成

掙扎起初,我可以做的工作「@View()」的註釋,因爲它總是會說,我的模板丟失了,沒有關係我會使用什麼配置選項我會得到相同的錯誤,然後在我的路由yml中添加「默認值:{_format:json}」,並突然聲明工作。

v1: 
    resource: "@AppBundle/Controller/" 
    defaults: { _format: json } 
    type:  annotation 
    prefix: /v1 

但隨着形式,現在我有問題,我創建了一個窗體類和服務,並建立簡單的控制器方法:

/** 
* Creates a new Order entity. 
* 
* @Rest\Post("/products", name="products_create") 
* @Rest\View() 
* @param Request $request 
* @return Product|array 
*/ 
public function createAction(Request $request) 
{ 
    $product = new Product(); 
    $form = $this->createForm('product', $product); 

    $form->handleRequest($request); 

    if ($form->isValid()) { 
     $em = $this->getDoctrine()->getManager(); 
     $em->persist($product); 
     $em->flush(); 

     return $product; 
    } 

    return $form; 
} 

如果現在的形式是這是在我的測試情況下無效的,我會期望獲得到類似的反應,即顯示在文檔:http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#forms-and-views

但不是這樣的:

{ 
    "code": 400, 
    "message": "Validation Failed"; 
    "errors": { 
     "children": { 
      "code": { 
       "errors": [ 
        "This value should not be blank." 
       ] 
      }, 
      "name": { 
       "errors": [ 
        "This value should not be blank." 
       ] 
      }, 
      "description": { 
       "errors": [ 
        "This value should not be blank." 
       ] 
      } 
     } 
    } 
} 

我得到:

{ 
    "children": { 
     "code": [], 
     "name": [], 
     "description": [] 
    } 
} 

這裏發生了什麼?我的設置有問題或我錯過了什麼?順便說一下,我在我的實體中設置了表單驗證

回答

2
{ 
"children": { 
    "code": [], 
    "name": [], 
    "description": [] 
    } 
} 

這意味着表單有效且驗證中沒有任何錯誤。所以,這是正確的迴應,因爲你說你的測試用例已經得到有效的表單。

從下面響應的片段將顯示如果字段將被定義爲在形式聲明以及與驗證約束NotBlank(http://symfony.com/doc/current/reference/constraints/NotBlank.html)「需要」。

"errors": [ 
       "This value should not be blank." 
] 

編輯:

的意見經過討論:與 「提交」 替換 「的handleRequest」 幫助。

+0

表單爲「無效」無效 –

+0

對不起,我的錯誤。您確定在實體中您將這些字段的驗證定義爲「NotBlank」嗎? – KLXN

+0

是的,我也嘗試直接在表單類中定義表單驗證,得到了相同的結果 –

0

我知道的解決了這個標記,但我最近遇到了同樣的問題與FOSRestBundle它在

http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#forms-and-views

被記錄的方式不是返回一個無效的形式,我發現實際問題有在使用JMS串行器的情況下,使用的順序在AppKernel中註冊軟件包。您必須確保按以下順序加載:

new JMS\SerializerBundle\JMSSerializerBundle(), 
new FOS\RestBundle\FOSRestBundle() 

一旦我做到了,我開始看到的結果與當表單驗證失敗的文檔一致。