简体   繁体   English

Symfony2学说插入/更新表格

[英]Symfony2 Doctrine insert/update form

I am trying to compose a very basic form which is capable of inserting and as well updating records in the database. 我正在尝试编写一个非常基本的表格,该表格能够插入和更新数据库中的记录。 My problem is that each time I press the Save button, a new row is created in the DB. 我的问题是,每当我按下“保存”按钮时,就会在数据库中创建一个新行。 Could you please point to the problem in my source code? 您能否在我的源代码中指出问题?

controller: http://pastebin.com/YjMAdHqp 控制器: http//pastebin.com/YjMAdHqp

routing: http://pastebin.com/WSV6xCSw 路由: http : //pastebin.com/WSV6xCSw

The id column in the database is an auto-increment integer. 数据库中的id列是一个自动递增的整数。

Thanks for any ideas. 感谢您的任何想法。

The right answer for your question is using merge method instead persist. 您问题的正确答案是使用merge方法而不是坚持。 eg: 例如:

$your_entity = $form->getData();
$this->em->merge($your_entity); // MERGE not PERSIST
$this->em->flush();

You can read more about Merge Method at the official documentation 您可以在官方文档中了解有关合并方法的更多信息

Cheers, 干杯,

  if ($id == 0) {
    $task = new Task();
  }

Your ID parameter defaults to 0 and a new Task is created instead of updating an existing tast. 您的ID参数默认为0,并且会创建一个新的Task而不是更新现有的tast。

hello_index:
    pattern: /hello/index/{id}
    defaults: { _controller: AcmeHelloBundle:hello:index, id:0 }

You should seperate create and edit/update action and create a routing for each action. 您应该分别创建和编辑/更新操作,并为每个操作创建路由。

http://symfony.com/doc/2.0/book/doctrine.html#updating-an-object http://symfony.com/doc/2.0/book/doctrine.html#updating-an-object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM