Symfony 4-避免更新数据库上未给定的字段

时间:2019-04-30 07:28:53

标签: php symfony doctrine

我已经构建了rest-api应用程序,但是如果我想更新实体,symfony会更改整个行。因此,在GET-Request中未指定的字段也将更改并设置为NULL。

我只想更新GET-Request中包含的字段。

public function update(int $id, Request $request, UserPasswordEncoderInterface $passwordEncoder) {
  $account = $this->repository->find($id);

  if ($account == null) {
    throw new HttpException(Response::HTTP_NOT_FOUND);
  }

  $form = $this->createForm(UserType::class, $account);
  $form->submit($request->request->all());

  if ($form->isSubmitted() && $form->isValid()):
    $account->setPassword(
      $passwordEncoder->encodePassword(
        $account,
        $form->get('password')->getData()
      )
    );
    $em = $this->getDoctrine()->getManager();
    try {
      $em->flush();
    } catch (\Exception $e) {
      throw new HttpException(Response::HTTP_BAD_REQUEST, $e->getMessage());
    }

    return $this->view(null, Response::HTTP_NO_CONTENT);
  else:
    return $this->view($form, Response::HTTP_BAD_REQUEST);
  endif;
 }

1 个答案:

答案 0 :(得分:5)

您必须将false作为第二个参数传递给$form->submit();这将禁用表单系统清除未提交值的默认行为。

https://symfony.com/doc/current/form/direct_submit.html#calling-form-submit-manually