Эта функция объясняется здесь
В моем первом контроллере я выполняю ограниченный запрос по датам, указанным оператором.
Код: Выделить всё
#[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('App\Controller\FuenteController::csvAction', [
'noticias' => $noticias
]);
return $response;
}
return $this->render('fuente/entrefechas.html.twig', array(
'form' => $form->createView() ));
}
Код: Выделить всё
#[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;
}
Когда я применяю эту функцию к загрузке, этого не происходит, но файл где-то генерируется в памяти или пространстве сервера. Откуда мне знать?
Если я поищу раздел Ajax на нижней панели инструментов, я увижу список сгенерированных, но не загруженных файлов.
Если мы нажмем на некоторые из этих ссылок на панели функций, загрузка осуществляется там.
Задача состоит в том, как добиться прямой загрузки
Подробнее здесь: https://stackoverflow.com/questions/789 ... d-function