如何在symfony2中编辑功能

时间:2014-02-18 05:14:00

标签: php symfony twig

我已经在symfony2中编写了一个编辑函数,我的问题是我可以从数据库中获取以前的值,但是在提交表单之后,未创建值而是创建了一个新表单

这是控制器

      public function editAction($id){
        $request = $this->getRequest();
    $em = $this->getDoctrine()->getEntityManager();
    $profile= $em->getRepository('TcprofileBundle:TcProfiles')
    ->find($id);

        $profile_form = $this->createForm(new ProfileType(), $profile);
        $response = new JsonResponse();
        $response->setData(array('content' => $this->renderView('TcprofileBundle:Default:create.html.twig',array('form' => $profile_form->createView()))));
        return $response;

}

Html.twig文件

 <div class="edit01"><a href="#!{{ path('tcprofile_edit',{ 'id': profile.getId}) }}"> Edit Profile </a></div>

我正在获取旧值,所以我将if循环用于条件检查,如此

控制器

 public function editAction($id){

    $request = $this->getRequest();
    $em = $this->getDoctrine()->getEntityManager();
    $profile= $em->getRepository('TcprofileBundle:TcProfiles')
    ->find($id);
    if(!$id){
    $profile_form = $this->createForm(new ProfileType(), $profile);
    $response = new JsonResponse();
    $response->setData(array('content' => $this->renderView('TcprofileBundle:Default:create.html.twig',array('form' => $profile_form->createView()))));
    return $response;
    }else{
        $profile->upload();
        $em->persist($profile);
        $em->flush();


    $response = new JsonResponse();
    $response->setData(array('content' => $this->renderView('TcprofileBundle:Default:create.html.twig',array('form' => $profile_form->createView()))));
    return $response;
 }
}

它没有得到输出如果我在某个地方出错了,请帮助我

1 个答案:

答案 0 :(得分:0)

更新实体时,您可以使用$em->merge($profile)代替$em->persist($profile)。请this stack overflow发布