0

I'm implementing editing user profile via API. The page where user edits its data contains a lot of fields, but when user submits the form, only edited fields are sent to my API endpoint. Also I'm not using form mapping.

Only way I see is to write something like this:

public function editProfile(FormInterface $form, User $user): User
{
    $args = $form->getData();

    if ($args['email']) {
        $user->setEmail($args['email']);
    }

    if ($args['phone']) {
        $user->setPhone($args['phone']);
    }

    // ...

    $this->em->persist($user);
    $this->em->flush();

    return $user;
}

But it looks terrible and my form may contain up to several tens of fields.

Does anybody know good solution for this case?

1
  • Why don't you use form mapping? Commented Jun 8, 2017 at 15:02

1 Answer 1

2

Use form mapping and submit form with disabled clear missing fields option:

In form builder:

$options->setDefaults([
    'data_class' => MyEntity:class
]);

In controller:

$data = $request->request->all();
$form->submit($data, false);` 

instead of $form->handleRequest($request);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.