【发布时间】:2011-10-12 09:23:07
【问题描述】:
在我正在构建的这个项目中,我有许多表单可以将数据添加到站点使用的数据库中。显然,如果用户添加了数据,他们必须能够编辑(或删除)这些数据。
我浏览了这本书,它详细讨论了使用表单添加数据。但是,它似乎没有提到如何使用表单来编辑数据。
如何做到这一点?
干杯
【问题讨论】:
标签: forms doctrine-orm symfony
在我正在构建的这个项目中,我有许多表单可以将数据添加到站点使用的数据库中。显然,如果用户添加了数据,他们必须能够编辑(或删除)这些数据。
我浏览了这本书,它详细讨论了使用表单添加数据。但是,它似乎没有提到如何使用表单来编辑数据。
如何做到这一点?
干杯
【问题讨论】:
标签: forms doctrine-orm symfony
如果你愿意,编写你的编辑操作很容易,不用教条,你应该这样做:
public function editAction( $id ) {
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('YourBundle:YourEntity');
$element = $repository->find( $id );
if ( false !== is_null( $element ) ) {
throw $this->createNotFoundException( 'Couldn\'t find element ' . $id . '!');
}
$form = $this->createForm( new YourFormType(), $element );
$request = $this->getRequest();
if ( $request->getMethod() == 'POST' ) {
$form->bindRequest( $request );
if ( $form->isValid() ) {
$em->persist( $element );
$em->flush();
$this->get( 'session' )->setFlash( 'system-message', 'Element Updated!' );
return $this->redirect( $this->generateUrl( 'Your_route' ) );
}
}
return $this->render('YourBundle:YourView:your_template.html.twig', array( 'element' => $element, 'form' => $form->createView() ) );}
edit 操作与 new 操作的唯一不同之处在于,您可以从实体管理器获取它,而不是创建一个新的“元素”实例,您甚至可以在将元素附加到表单之前为其设置任意值。
希望对你有帮助!
【讨论】:
使用generate:doctrine:crud 任务生成用于编辑/更新用户的代码。您会看到 newAction 和 editAction 非常相似。
【讨论】: