How to persist a collection of forms embedded in a collection of Forms…?

For my Poll Application i created a FormType called CampaignType which holds a CollectionType named blocks which in turn holds a CollectionType named lines, which holds a CollectionType named fields, which holds a CollectionType named pollResults.

In my next code example you can see my code that renders the View to fill a campaign(poll).

public function fillAction(Request $request, $id)
{
    $campaign = $this->getDoctrine()->getRepository(Campaign::class)->find($id);
    $entityManager = $this->getDoctrine()->getManager();

    foreach ($campaign->getBlocks() AS $block){
        foreach ($block->getLines() AS $line){
            foreach ($line->getFields() AS $field){

                $pollResult = new PollResult();
                $pollResult->setCampaign($campaign);
                $pollResult->setField($field);
                $pollResult->setUser($this->getUser());

                $entityManager->persist($pollResult);

                $field->getPollResults()->add($pollResult);
            }
        }
    }

    $form = $this->createForm(CampaignType::class, $campaign);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()){
        var_dump("true");
        //$entityManager->persist($campaign);
        $entityManager->flush();
        return $this->redirectToRoute("grappt_poll_campaignShow", ['id' => $id]);
    }

    return $this->render('GrapptPollBundle:Campaigns:fill.html.twig', [
        'campaign' => $campaign,
        'form' => $form->createView()
    ]);
}

The only thing that must be persisted in the database are the PollResults.
Every PollResult has an entry for the campaign_id and the field_id it belongs to, the user_id who filled out the campaign and the value the user chose (and of course its own id, which gets generated automatically).

My Problem is that i don’t know how to do that.
Where do i have to call $entityManager->persist($pollResult);.
Right now i put it directly under the initialization-stuff.
Do i have to put it into the if($form->isSubmitted() && $form->isValid())-query and loop through every pollResult?
Do i have to call $entityManager->persist($campaign); although nothing changes there?
Furthermore i wonder if i have to add something for the value-entry of each PollResult?

Thanks in advance for every answer

lxg

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *