0

The code below downloads the current file, I need it to open the file in a new tab, what needs to be added in order to do so?

public function submitForm(array &$form, FormStateInterface $form_state) {
     $filename = '/var/www/html/web/modules/custom/custom_module/sample.pdf';
     $response = new BinaryFileResponse($filename);
     $response->setContentDisposition(
          ResponseHeaderBag::DISPOSITION_ATTACHMENT,
          'sample.pdf'
     );
     $form_state->setResponse($response);
  • That’s not possible, tabs can only be opened by client-side code – Clive Jul 23 '18 at 16:03
0

As @clive points out, this cannot be done on the server side. Check this post for a javascript based solution. You need to attach the javascript to your form during build. See below for an example of form build with a javascript attached to the submit element:

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  // Assuming you are extending core \Drupal\Core\Form\FormBase class
  // and prior the lines below you built your form elements.
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Download file'),
    '#button_type' => 'primary',
    '#attached' => [
      'library' => 'your_module/submitToNewTab'
    ]
  ];

  return $form;
}

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.