skip to Main Content

The problem is to send data from one controller to another controller using Symfony’s forward function.
The function is explained here

In my first controller, I perform a query bounded by dates supplied by the operator.

#[Route('/admin/fuente/exportar0/', name: 'app_exportar0_fuente', methods: ['GET', 'POST'])]
    public function exportar0(Request $request, FuenteRepository $fuenteRepository, CSVResponse $CSVResponse): Response
    {
           $defaultData = [];
    $form = $this->createFormBuilder($defaultData, ['method' => Request::METHOD_GET])
            
        ->add('fecha_desde', DateType::class, array(
                'label'    => 'Fecha desde?: ', 
                'input'=>'string', 'required' => true,  
            'widget' => 'single_text',
        'attr' => array('style' => 'width: 120px'), 

            ))
        ->add('fecha_hasta', DateType::class, array(
                'label'    => 'Fecha hasta?: ', 
                'input'=>'string', 'required' => true, 
              'widget' => 'single_text',
             'attr' => array('style' => 'width: 120px'),

                ))
         ->add('save', SubmitType::class, ['label' => 'Buscar'])

        ->getForm();

        $form->handleRequest($request);
       
        

      if($form->isSubmitted()&&$form->isValid()){

        // datafecha is an array with "fecha_desde", and "fecha_hasta" keys 
        
       $datafechas = $form->getData();

       $noticias = $fuenteRepository->findTodosCSV($datafechas);
       
       $response = $this->forward('AppControllerFuenteController::csvAction', [
       
        'noticias' => $noticias
    ]);

      return $response;
      

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

In the second controller, I use the result of the query from the previous controller to generate a csv file and download it.

 #[Route('/admin/fuente/csv/', name: 'app_csv_fuente', methods: ['GET', 'POST'])]
            public function csvAction(array $noticias ): Response
    {           

        $data=array();
       
        $data[0]= array("Id","Diario","Link", "Palabras","Título","Contenido","Fecha","Mes", "Año",
        "Protagonista", "Dinámica Conflictual", "Sector", "Sub sector", "Departamento","Pertenencia",
        "Agrupación", "Agregación", "Antagonista", "Actor Estatal","Nivel de Gobierno", "Participación",
        "Protagonista", "Respuesta Patronal 1","Respuesta Patronal 2", "Respuesta Estado 1", "Respuesta Estado 2",
   "Demanda 1 nombre", "Demanda 1 principal","Demanda 2 nombre","Demanda 2 principal", 
    "Demanda 3 nombre", "Demanda 3 principal", "Actor emergente",
     "Formato","Formato 2","Formato 3",     
);
       $i=1;
     
        foreach ($noticias as $noticia) {
         
         $data[$i]= array(
              $noticia['id'],
               $noticia['diario'],
               $noticia['link'],
               $noticia['palabras'],
               $noticia['titulo'],
               $noticia['contenido'],
               $noticia['fecha']->format('d-m-Y'),
               $noticia['fecha']->format('F'),
               $noticia['fecha']->format('Y'),
               $noticia['protagonista_name'],
               $noticia['actividad_name'],  
               $noticia['sector_name'],
               $noticia['subsector_name'],
               $noticia['Departamento'],
               $noticia['Pertenencia'],
               $noticia['Agrupacion'],
               $noticia['Agregacion'],
               $noticia['Antagonista'],
               $noticia['Actorestatal'],
               $noticia['Nivelgobierno'],
               $noticia['Participacion'],
               $noticia['protagonista_name'],
               $noticia['respuestapatronal_name'],
               $noticia['respuestapatronal1_name'],
               $noticia['respuestaestado_name'],
               $noticia['respuestaestado1_name'],
               $noticia['demanda1_name'],
               $noticia['principal1_name'],
               $noticia['demanda2_name'],
               $noticia['principal2_name'],
               $noticia['demanda3_name'],
               $noticia['principal3_name'],
               $noticia['Actoremergente'],
               $noticia['protesta_name'],
               $noticia['protesta_name2'],
               $noticia['protesta_name3'] ,        
       ); 
         $i++;
           }  
       
            
              $fp = fopen('php://memory','w', "w");
              foreach($data as $fields){
                fputcsv($fp, $fields, ';');
              }
              rewind($fp);

              $response = new Response(stream_get_contents($fp));
              fclose($fp);
              $response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
              $response->headers->set('Content-Encoding', 'UTF-8');
              $response->headers->set('Cache-Control', 'private');
              
              $response->headers->set('Content-Disposition', 'attachment; filename="noticias.csv"');
              $response->sendHeaders();
            
              
              return $response;

            }           

The problem is that the download does not work but the csv file is created!
When I apply this function to a download, it does not occur but the file is generated somewhere in memory or server space. How do I know?
If I look for the Ajax section in the bottom toolbar, I can see the list of files generated but not downloaded.
If we click on some of these links in the function bar, the download is achieved there.
The challenge is how to achieve a direct download

2

Answers


  1. You will need to open the stream also for reading if you later want to get the contents.

    $fp = fopen('php://memory','rw');
    foreach($data as $fields){
        fputcsv($fp, $fields, ';');
    }
    rewind($fp);
    
    $response = new Response(stream_get_contents($fp));
    fclose($fp);
    
    Login or Signup to reply.
  2. I think this maybe little weird but you can try to put the download code inside a sperate function and call it after ensuring the file creation then call it by passing the file path.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search