1

I have created a form which has only a submit button. In the submit function I am generating csv file and saving it to the files folder using fputcsv function.

But Now I need extra functionality of submit. After saving the file it should download the file also.

How to do this? Any one have some idea about this?

4 Answers 4

2

Attach a form submit handler (code here: Drupal 7 custom form submit handler is not being called).

Then set the file url to $form_state['redirect'].

The file download should begin when submitted.

3

In Drupal 8 to have the file download rather than redirect to it you can use:

$uri = $file->getFileUri();
  $headers = array(
    'Content-Type'     => $file->getMimeType(),
    'Content-Disposition' => 'attachment;filename="'.$file->getFilename().'"'
  );
  $form_state->setResponse(new \Symfony\Component\HttpFoundation\BinaryFileResponse($uri, 200, $headers, true));
1

In the following code I am downloading file as attachment created with phpExcel. It may help someone.

function dn_preorder_form_submit($form,&$form_state){   
                $excel = new PHPExcel();
                $excel->setActiveSheetIndex(0);
                $excel->getActiveSheet()->setCellValue('A1',"TEST");

                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment; filename="var.xlsx"');
                header("Pragma: no-cache");
                header("Cache-Control: no-cache");
                header("Cache-Control: nmax-age=0");

                $file = PHPExcel_IOFactory::createWriter($excel,'Excel2007');

                $file->save('php://output');
                exit();
    }
0

Assuming you are using a file stream, and Drupal specific

$filename = "report.csv";
$stream = "public://";
$uri = $stream . $filename; // Better to add a subfolder per context

$headers = [
  'Content-Type' => 'text/csv',
  'Content-Description' => 'File Download',
  'Content-Disposition' => 'attachment; filename="' . $filename . '"'
];

$rfh = fopen($uri, 'w');

fputcsv($rfh, ['ID', 'Mail', 'Name']);
fputcsv($rfh, ['1', '[email protected]', 'Jaffe Joffer']);

fclose($rfh);

$form_state->setResponse(new \Symfony\Component\HttpFoundation\BinaryFileResponse($uri, 200, $headers, true));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.