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);
  • That’s not possible, tabs can only be opened by client-side code
    – Clive
    Commented Jul 23, 2018 at 16:03

2 Answers 2


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;

I was able to open the results of a form in a new tab, like this:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#attributes'] = ['target' => '_blank'];

public function submitForm(array &$form, FormStateInterface $form_state) {
    ['node' => $calendarNid, 'startDate' =>  $startDate]


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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