-->

Symfony3 : multi-steps form and flush after forwar

2019-08-27 16:55发布

问题:

I have a form to add a new prescriber in my database. The first step consists in informing the various informations about the prescriber.

Then, I check if there are similar prescribers before adding it (2nd step with a 2nd form) and if there are, I ask the user to confirm.

In short, I have a 1-step form or a 2-steps form, depending on duplicates.

I tried with CraueFormFlowBundle but I don't know how to implement my conditional second step. My tests were inconclusive. So I decided to use forward method in my controller, and I like it !

But, I can't manage to flush my prescriber at the end of the 2nd step (after forwarding), I have this error : Unable to guess how to get a Doctrine instance from the request information for parameter "prescriber".

addAction (= step 1)

/**
 * Add a new prescriber
 *
 * @Route("/prescribers/add", name="prescriber_add")
 */
public function addAction(Request $request) {
    $em = $this->getDoctrine()->getManager();
    $rp = $em->getRepository('AppBundle:Prescriber');
    $p  = new Prescriber();

    // build the form
    $form = $this->createForm(AddPrescriberType::class, $p);

    // handle the submit
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        # search if a prescriber already exists
        $qb = $rp->createQueryBuilder('p');
        $qb->where($qb->expr()->eq('p.rpps', ':rpps'))
            ->orWhere($qb->expr()->andX(
                $qb->expr()->like('p.lastname', ':name'),
                $qb->expr()->like('p.firstname', ':firstname')
            ))
            ->setParameter('rpps', $p->getRpps())
            ->setParameter('name', '%'.$p->getLastname().'%')
            ->setParameter('firstname', '%'.$p->getFirstname().'%');

        $duplicates = $qb->getQuery()->getArrayResult();

        # there are duplicates
        if (!empty($duplicates)) {
            $em->persist($p);

            // confirm the addition of the new prescriber
            $params = array('prescriber' => $p, 'duplicates' => $duplicates);
            $query = $request->query->all();
            return $this->forward('AppBundle:Prescriber:addConfirm', $params, $query);

        } else {
            $em->persist($p);       # save the prescriber
            $em->flush();           # update database

            $this->addFlash('p_success', 'The prescriber has been created successfully');
            return $this->redirectToRoute('prescriber');
        }
    }

    // show form
    return $this->render('prescribers/form-step1.html.twig', array(
        'form' => $form->createView()
    ));
}

addConfirmAction (= step 2)

/**
 * Confirm addition of a new prescriber
 *
 * @Route("/prescribers/add/confirm", name="prescriber_add_confirm")
 */
public function addConfirmAction(Prescriber $prescriber, $duplicates, Request $request) {
    $em = $this->getDoctrine()->getManager();

    $form = $this->createFormBuilder()->getForm();

    if ($form->handleRequest($request)->isValid()) {
      $em->persist($prescriber);
      $em->flush();

      $this->addFlash('p_success', 'Prescriber has been created successfully');
      return $this->redirectToRoute('prescriber');
    }

    // show confirm page
    return $this->render('prescribers/form-step2.html.twig', array(
      'h1_title'  => 'Ajouter un nouveau prescripteur',
      'form'      => $form->createView(),
      'p'         => $prescriber,
      'duplicates'=> $duplicates
  ));
}

I think the problem comes from the fact that I have 2 forms submissions...

回答1:

I found a solution by using the session. (I know it's not a perfect way but I didn't find other one)

For Symfony 3.3.*

use Symfony\Component\HttpFoundation\Session\SessionInterface;

public function addAction(Request $request, SessionInterface $session) {
    // [...]

    # there are duplicates
    if (!empty($duplicates)) {
        $data = $form->getData();
        $session->set('prescriber', $data);
        $session->set('duplicates', $duplicates);

        return $this->forward('AppBundle:Prescriber:addConfirm');

    // [...]
}

public function addConfirmAction(Request $request, SessionInterface $session) {
    $em   = $this->getDoctrine()->getManager();
    $p    = $session->get('prescriber');
    $duplicates = $session->get('duplicates');

    // empty form with only a CSRF field
    $form = $this->createFormBuilder()->getForm();

    if ($form->handleRequest($request)->isValid()) {
        $em->persist($p);
        $em->flush();

        $this->addFlash('p_success', 'The prescriber has been created successfully');
        return $this->redirectToRoute('prescriber');
    }

    // show confirm page
    return $this->render('prescribers/form-step2.html.twig', array(
       'form'      => $form->createView(),
       'prescriber'=> $p,
       'duplicates'=> $duplicates
    ));
}