user3786081
user3786081

Reputation: 177

Symfony 4 - avoid to update not given fields on database

I've built a rest-api application but if i want to update an entity, symfony changes the complete row. So fields, which are not given in the GET-Request are also changed and set to NULL.

I just want to update the fields which are contained in the 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;
 }

Upvotes: 0

Views: 605

Answers (1)

emarref
emarref

Reputation: 1311

You must pass false as the second argument to $form->submit(); This disables the Form system's default behaviour of clearing the values that were not submitted.

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

Upvotes: 6

Related Questions