0

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.

Edit#1

I have updated the generateCSV() code to include:

$response = new BinaryFileResponse($path . $filename);
$response->setContentDisposition(
  ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  $filename
);

$form_state->setResponse($response);

This is not invoking a download.

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);

  $response = new BinaryFileResponse($path . $filename);
  $response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    $filename
  );

  $form_state->setResponse($response);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.