2013-12-10 47 views
5

假設此表單利用Animal文檔對象類別ZooCollection,該文檔對象類別在中只有兩個屬性(「名稱」和「顏色」)。Symfony2使用數據形成預填充字段

我在尋找一個工作簡單愚蠢的方案,以預填表單字段與給定對象自動神奇(如更新?)。

Acme/DemoBundle/Controller/CustomController

public function updateAnimalAction(Request $request) 
{ 
    ... 
    // Create the form and handle the request 
    $form = $this->createForm(AnimalType(), $animal); 

    // Set the data again   << doesn't work ? 
    $form->setData($form->getData()); 
    $form->handleRequest($request); 
    ... 
} 
+0

大約只需設置動物對象的屬性是什麼? –

回答

6

您應該加載動物對象,你婉更新。 createForm()將使用加載的對象填充表單中的字段。

假設你正在使用註解來定義你的路由:

/** 
* @Route("/animal/{animal}") 
* @Method("PUT") 
*/ 
public function updateAnimalAction(Request $request, Animal $animal) { 
    $form = $this->createForm(AnimalType(), $animal, array(
     'method' => 'PUT', // You have to specify the method, if you are using PUT 
          // method otherwise handleRequest() can't 
          // process your request. 
    )); 

    $form->handleRequest($request); 
    if ($form->isValid()) { 
     ... 
    } 
    ... 
} 

我認爲它總是一個好主意,由Symfony和學說控制檯命令(doctrine:generate:crud)生成的代碼學習。你可以學習這個想法和你應該處理這種類型的請求的方式。

1

使用對象創建表單是最好的方法(請參閱@ dtengeri的回答)。但是你也可以使用$form->setData()和一個關聯數組,這聽起來像你所要求的。這在不使用ORM時很有用,或者您只需更改表單數據的子集。

大量疑難雜症是,在你的表單生成任何默認值將setData()覆蓋。這是違反直覺的,但這是Symfony的工作原理。討論: