G
G
gitdev2021-01-19 15:01:41
symfony
gitdev, 2021-01-19 15:01:41

Is it possible and necessary and is it necessary to take the Symfony form to the service, or is it better to leave it in the controller?

1. Is it possible to take the form to the service?
2. Do I need to take out the form?
3. Is it possible to transfer this code (except for view rendering) to a service (do they write like this)?

public function present(Proposition $proposition, Request $request, CVService $CVService): Response
    {
        $candidate = new Candidate();
        $form = $this->createForm(CandidateType::class, $candidate);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            if($CVService->present($proposition, $candidate)) {
                $this->addFlash(
                    'success',
                    'CV was sent'
                );
            } else {
                $this->addFlash(
                    'error',
                    'We got an error, CV was not sent'
                );
            }
            $candidate = new Candidate();
            $form = $this->createForm(CandidateType::class, $candidate);
        }
        return $this->render('cv/present.html.twig', [
            'form' => $form->createView(),
        ]);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Flying, 2021-01-19
@gitdev

  1. Symfony best practices recommend , yes
  2. Actually see item 1. In particular, this improves the maintainability of the code, especially in the case of more or less complex forms or forms that require additional initialization / configuration logic. Actually, your code just uses the form as a service, try copying the contents of the class CandidateTypehere and compare the resulting code.
  3. The form processing code is most likely not worth taking out to the service. it is directly tied to the Request=> transformation Response, and that's what controllers are for.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question