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

use*_*081 0 php doctrine symfony

我已经建立了一个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;
 }
Run Code Online (Sandbox Code Playgroud)

ema*_*ref 5

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

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