Symfony-控制器编辑操作?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (43)

我在控制器中定义了表单,并设置函数来编辑/更新我可以通过ID找到的特定字段。我找不到我做错了什么.。

 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();
}

服务

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();
    }
}
提问于
用户回答回答于

Symfony returns是按find主键(通常id)搜索时的单个对象,然后你可以检查是否存在返回单个对象Entity(在这种情况下User),以便通过使用进行检查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
    }
}

扫码关注云+社区

领取腾讯云代金券