-1

In the form builder I have the following code.

$form['export_to_pdf'] = [
  '#type' => 'submit',
  '#value' => $this->t('Pdf Format'),
  '#attributes' => array('name'=>'print_pdf',),
  '#ajax'=> array(
    'callback' => '::exportPdf',
    'event' => 'click',
    'effect' => 'fade',
    'prevent' => 'submit',
    'progress' => array(
      'type' => 'throbber',
      'message' => t('Retrieving...'),
    ),
  ),
];

The callback function is the following one.

public function exportPdf(array &$form, FormStateInterface $form_state) { 
  global $base_url;
  $url = "{$base_url}/pdf_templates/report.pdf";
  $response = new AjaxResponse();
  $response->addCommand(new RedirectCommand($url));
  return $response;
}

This works, but it doesn't pop up the Open/Save file dialog. It redirects to the PDF file. How do I make the callback show the Open/Save file dialog so that the users can either open or save according to their wish?

0

For Open /Save Dialog pop up you can use following ajax commands in the ajax callback

1.OpenModalDialogCommand
2.OpenDialogCommand

Don't forget to include following namespaces

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\OpenDialogCommand;

In your ajax callback function add like below:
 $content = AjaxTestController::dialogContents();
 $response = new AjaxResponse();
$title = $this->t('AJAX Dialog & contents');

Attach the library necessary for using the Open(Modal)DialogCommand and set the attachments for this Ajax response.

$content['#attached']['library'][] = 'core/drupal.dialog.ajax';

if you need as modal dialog you can use below statement

$response->addCommand(new OpenModalDialogCommand($title,
$content));

or only dialog type

 $selector = '#ajax-test-dialog-wrapper-1';
    $response->addCommand(new OpenDialogCommand($selector, $title, $content);

return $response;

for any reference you can check below files in the drupal directory

core/modules/system/tests/modules/ajax_test/src/form/AjaxTestDialogForm

After completing the dialog command ,you can use your redirect command to continue

  • Is there no way to use the browser in-built Open/Save file dialog because your answer will require repeating the code behind these in-built Open/Save file dialog. – Mundile Aug 21 '17 at 9:47

Your Answer

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

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