Skip to main content
1 of 2
WRD
  • 329
  • 5
  • 17

I was off-track in even trying to do this with AJAX, as Clive mentioned in his comment. Instead, I just made it a normal submit button, and then overrode the form action. The result is that the data is downloaded as a file, the form doesn't reload, and the data output section doesn't update, which is the desired behavior in this case.

The button, along with a new format element:

$form['download']['format'] = [ '#type' => 'select', '#options' => $this->getValidFormats(), '#title' => $this->t('Select format'), '#weight' => '0', ]; $form['download']['download'] = [ '#type' => 'submit', '#value' => $this->t('Download'), '#weight' => '10', ]; 

The submit function:

public function submitForm(array &$form, FormStateInterface $form_state) { switch ($form_state->getValue('op')->__toString()) { case 'Download': $this->download($form, $form_state); break; } } 

And the relevant part of the download function:

$response = new Response($file_content); $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'data.' . $format); $response->headers->set('Content-type', $content_types[$format]); $response->headers->set('Content-Disposition', $disposition); $response->headers->set('Content-Transfer-Encoding', 'binary'); $response->headers->set('Content-length', strlen($file_content)); $form_state->setResponse($response); 
WRD
  • 329
  • 5
  • 17