[英]Symfony2 Form pre-fill fields with data
假設此時,這種形式利用的假想Animal
文檔對象類從ZooCollection
只有兩個在性質(“name”和“顏色”) 的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);
...
}
您應該加載要更新的動物對象。 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 生成的代碼和學說控制台命令( 學說:generate:crud )中學習總是一個好主意。 您可以了解處理此類請求的想法和方式。
使用對象創建表單是最好的方法(請參閱@dtengeri 的回答)。 但是您也可以將$form->setData()
與關聯數組一起使用,這聽起來像您所要求的。 這在不使用 ORM 或您只需要更改表單數據的子集時很有用。
最大的問題是表單構建器中的任何默認值都不會被setData()
覆蓋。 這是違反直覺的,但這就是 Symfony 的工作方式。 討論:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.