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

问题描述 投票:0回答:1

我已经构建了一个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;
 }
php symfony doctrine
1个回答
5
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.