/**
  * Success page after reference purchase
  *
  * @Route()
  * @Method({"GET", "POST"})
  * @Template()
  *
  * @param Request $request
  * @return array
  * @throws CaseNotSubmittedException
  */
 public function indexAction(Request $request)
 {
     // Get the submitted case
     /** @var ReferencingCase $case */
     $case = unserialize($request->getSession()->get('submitted-case'));
     if (false === $case) {
         // Failed to retrieve case from session
         throw new CaseNotSubmittedException('submitted-case could not be retrieved from the session.');
     }
     // Flatten application/guarantor hierarchy in depth first search order
     // todo: only needs doing for applications who are completing now
     $applications = array();
     foreach ($case->getApplications() as $application) {
         $applications[] = $application;
         if (null !== $application->getGuarantors()) {
             foreach ($application->getGuarantors() as $guarantor) {
                 $applications[] = $guarantor;
             }
         }
     }
     $tenancyAgreement = new TenancyAgreement();
     $tenancyAgreement->setApplications($applications);
     // Create form, with flattened data
     $form = $this->createForm(new TenancyAgreementType(), $tenancyAgreement);
     $form->handleRequest($request);
     if ($form->isValid()) {
         // Persist each application/guarantor model with the updated marketing preferences
         /** @var AbstractReferencingApplication $application */
         foreach ($applications as $application) {
             $this->irisEntityManager->persist($application, array('caseId' => $case->getCaseId(), 'applicationId' => $application->getApplicationId()));
         }
         // Submit the entire case
         $case->submit($this->irisEntityManager->getClient());
         // Flush the case/applications from the session for the next reference
         $request->getSession()->remove('submitted-case');
         return $this->redirect($this->generateUrl('barbon_hostedapi_agent_reference_cases_view_index', array('caseId' => $case->getCaseId())));
     }
     return array('form' => $form->createView());
 }
 /**
  * @param array $applications
  * @return \Symfony\Component\Form\Form
  */
 protected function buildTenancyAgreementForm(array $applications)
 {
     $tenancyAgreement = new TenancyAgreement();
     $tenancyAgreement->setApplications($applications);
     return $this->createForm(new TenancyAgreementType(), $tenancyAgreement, array('user_type' => 'landlord'));
 }