Prompt user to download file via AJAX form submission

by FatGuyLaughing   Last Updated May 15, 2019 23:07 PM

I have a file that is generated when an AJAX button is clicked. I want to immediately have a file download prompt come up. The file is being generated and has the correct data in the file. I just don't know how to force the download prompt to come up.

AJAX Button

$form['comp_card_dl'] = [
  '#type' => 'button',
  '#value' => $this->t('Download'),
  '#ajax' => [
    'callback' => '::generateCSV',
    'progress' => [
      'type' => 'throbber',
    ],
  ],
  '#name' => 'comp_card_download',
];

CSV File Creation

public function generateCSV($form, FormStateInterface $form_state) {
  $trigger = $form_state->getTriggeringElement();
  if ($trigger['#name'] == 'gift_card_download') {
    $filename = $form['#gift_card_filename'];
    $data = $form['#gift_card_data'];
  }
  else if ($trigger['#name'] == 'comp_card_download') {
    $filename = $form['#comp_card_filename'];
    $data = $form['#comp_card_data'];
  }

  $path = \Drupal::service('file_system')->realpath(file_default_scheme() . "://") . '/';
  $csv = fopen($path . $filename, 'w');

  foreach ($data as $id => $value) {
    array_unshift($value, $id);
    fputcsv($csv, $value);
  }

  fclose($csv);
}
Tags : 8 files


Related Questions


Updated August 12, 2016 08:03 AM

Updated September 01, 2016 08:04 AM

Updated February 15, 2017 14:03 PM

Updated March 14, 2017 14:07 PM

Updated August 23, 2015 17:03 PM