3

I have a custom module where I need to create a file and download it on form submission. So far, I managed to created the file and save it in public folder, but I cannot find a way to download it to client. This is the code I wrote so far.

public function submitForm(array &$form, FormStateInterface $form_state) {
  $file_name = $date.'-event.ics';
  $cal_file = file_unmanaged_save_data('file content',"public://cal/$file_name",FILE_EXISTS_RENAME);
  return new RedirectResponse(file_create_url("public://cal/211443-event.ics"));
}

2 Answers 2

5

You can return a BinaryFileResponse from a controller, or as 4k4 has added:

$response = new BinaryFileResponse("public://cal/211443-event.ics");
$form_state->setResponse($response);
6
  • 1
    This is what you want.
    – Kevin
    Commented Mar 29, 2019 at 23:46
  • 1
    Yes, return it from a controller or set it directly in $form_state: $form_state->setResponse($response);
    – 4uk4
    Commented Mar 30, 2019 at 9:30
  • 1
    Nice. I didn’t know that. I’ll edit my post to include it.
    – Jaypan
    Commented Mar 30, 2019 at 9:31
  • 1
    Thank you for the response. I ll try it and I ll post the results here Commented Mar 31, 2019 at 12:01
  • 1
    You might be able to remove the call to file_create_url(). Let me know if that's the case and I'll update.
    – Jaypan
    Commented Mar 31, 2019 at 12:47
2

That is what, for example, the Drupal\locale\Form\ExportForm class does. See the code used in ExportForm::submitForm().

$response = new BinaryFileResponse($uri);
$response->setContentDisposition('attachment', $filename);
$form_state->setResponse($response);

$response->setContentDisposition() sets the Content-Disposition header with the given filename. That is the filename used for the Save file dialog the browser will show to users.

1
  • 1
    Thank you for the response. Very useful Commented Mar 31, 2019 at 12:02

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.