douhuan3420 2018-06-04 12:24
浏览 50
已采纳

Symfony - 控制器编辑操作

I defined the form in my controller and set function to edit/update specific fields that I can find by ID. I can't find what am I doing wrong..

 public function getUserEdit(Request $request)
{
    $form = $this->createFormBuilder()
        ->add('firstName', TextType::class, array('label' => 'First Name*', 'attr' => ['class'=>'form-control']))
        ->add('save', SubmitType::class, array('label' => 'Send', 'attr' => [
            'class' => 'btn btn-primary action-save'
        ]))
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $data = $form->getData();
        $firstName = $data['firstName'];

        $this->container->get('user')->editUser($firstName);
    }

    return $this->success();
}

Service

public function editUser($id)
{
    $editUsers = $this->getUserRepository()->find($id);

    if(empty($editUsers)) {
        $editUsers = new User();
        $editUsers->setId($id);
        $this->em->persist($editUsers);
        $this->em->flush();
    }
}
  • 写回答

1条回答 默认 最新

  • duandi4238 2018-06-04 13:34
    关注

    Symfony returns a single object when searching by find primary key (usually id), then you can check if exist returns a single Entity (in this case User) and so that checking by using insteance.

    public function editUser($id)
    {
        $editUsers = $this->getUserRepository()->find($id);
    
        if($editUsers insteance User) { // here just check 
            //$editUsers = new User(); // here You don't need create new object of class User, just remove
            $editUsers->setId($id);
            $this->em->persist($editUsers);
            $this->em->flush();
        }
        else {
            // do something if you need
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Workbench中材料库无法更新,如何解决?
  • ¥20 如何推断此服务器配置
  • ¥15 关于github的项目怎么在pycharm上面运行
  • ¥15 内存地址视频流转RTMP
  • ¥100 有偿,谁有移远的EC200S固件和最新的Qflsh工具。
  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败