I think would be very useful to have the ability to set in "Display Field Settings" and Views an option to have the file open a new window. This can be easily themed, but for non-coders this would be a simple, handy feature. Thanks! Let me know if I can help in any way.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

Mac Clemmens’s picture

To build on this idea, what about having some options like:

Display Filename as Link to File
Display Node Title as Link to File
Display Filename as Link to File in New Window
Display Node Title as Link to File in New Window
etc.,

anthonym’s picture

For Views, I would love to have an icon-only field display option for table views. Right now, there is only the "Default" option which shows title (as link) and icon.

dopry’s picture

Status: Active » Closed (won't fix)

Write your own formatter... This isn't going into filefield.

raintonr’s picture

Version: 5.x-2.x-dev » 6.x-3.2
Status: Closed (won't fix) » Active

Unless I can't see it anywhere this feature didn't get implemented in D6 version. Such an option would be very useful.

quicksketch’s picture

We discussed this once in the D6 queue and I did implement the link opening in a new window, but only on the node edit form, since leaving the page would cause your new uploads to be lost. However this still won't be added to the front-facing file display. I'd suggest putting some jQuery in your theme such as this:

$('.filefield-file a').attr('target', '_blank');

Or you can use any number of popup scripts out there to make your files open in a window that is a certain size.

quicksketch’s picture

Status: Active » Closed (won't fix)
ali_b’s picture

edit function theme_filefield_file in filefield_formatter.inc
best way is to add to your template.php:

function youtemplatename_filefield_file($file) {
  // Views may call this function with a NULL value, return an empty string.
  if (empty($file['fid'])) {
    return '';
  }

  $path = $file['filepath'];
  $url = file_create_url($path);
  $icon = theme('filefield_icon', $file);

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  // TODO: Possibly move to until I move to the more complex format described 
  // at http://darrelopry.com/story/microformats-and-media-rfc-if-you-js-or-css
  $options = array(
    'attributes' => array(
      'type' => $file['filemime'] . '; length=' . $file['filesize'],
    ),
  );

  // Use the description as the link text if available.
  if (empty($file['data']['description'])) {
    $link_text = $file['filename'];
  }
  else {
    $link_text = $file['data']['description'];
    $options['attributes']['title'] = $file['filename'];
  }
//open allfiles in new window
$options['attributes']['target'] = '_blank';

  return '<div class="filefield-file clear-block">'. $icon . l($link_text, $url, $options) .'</div>';
}
Xagarsan’s picture

Ok!, it is everything correct.

Thank you very much, I brought while attempting to find the solution.

Sincerely,

Xavier Garcia

dppeak’s picture

Try the following with slight modifications to open in a new window based on the MIME type. The idea was borrowed from an idea jpetso said here http://drupal.org/node/190566.

function youtemplatename_filefield_file($file) {
  // Views may call this function with a NULL value, return an empty string.
  if (empty($file['fid'])) {
    return '';
  }

  $path = $file['filepath'];
  $url = file_create_url($path);
  $icon = theme('filefield_icon', $file);

  // Set options as per anchor format described at
  $options = array(
    'attributes' => array(
      'type' => $file['filemime'] . '; length=' . $file['filesize'],
    ),
  );

  // Use the description as the link text if available.
  if (empty($file['data']['description'])) {
    $link_text = $file['filename'];
  }
  else {
    $link_text = $file['data']['description'];
    $options['attributes']['title'] = $file['filename'];
  }

  //open files of particular mime types in new window
  $new_window_mimetypes = array(
    'application/pdf',
    'text/plain'
  );
  if (in_array($file['filemime'], $new_window_mimetypes)) {
    $options['attributes']['target'] = '_blank';
  }

  return '<div class="filefield-file clear-block">'. $icon . l($link_text, $url, $options) .'</div>';
}
maverick14’s picture

I like the suggested solution in #1. That would be very cool.

freatida’s picture

#7 works great for me. Thanks for posting.

leon85321’s picture

#7 resolve my problem too, great job!

aiphes’s picture

#7 solve my interrogation...great thx

gustavoiranzo’s picture

#7 and #9 solve my problen ...great
Thanks ali_b and dppeak

davepoon’s picture

#7 and #9 solutions are great! Thanks!

arpieb’s picture

I wound up going with #9, which works fine but shouldn't be required just to get this kind of functionality, IMNSHO. I had to update code in SVN, migrate the changes onto a server, test it, etc before deploying when it would have been great to have either told the client (or done it myself) to just click a checkbox that said "Open in new window" on the field settings page and hit "Save Settings."

The Link CCK field offers it as an option on its field (along with quite a few other nice options like link text on/off/optional/static which would have been handy on so many occassions for this field, but I digress), not quite sure why there is so much resistance to adding this feature when so many people have asked for it?

It'd make the module a lot more user-friendly for those people setting up Drupal sites that are not ripping into the template files, or people administering sites that have no clue how (and whose job it isn't) to hack on a template file...

thrash632’s picture

I agree with #16, couldn't said it better myself.

User friendliness is key.

Danny Englander’s picture

Thank you for this, exactly what I needed. #9 worked great.

meirbr’s picture

#9 worked great when i changed in the filefield_formatter.inc
but when i copy this function to mu template.php it doesnt work!!!!
what is my problem?????

manuel.adan’s picture

Status: Closed (won't fix) » Needs review
Issue tags: +Field Display
FileSize
55.75 KB

Hi,

Code base solution (in theme template.php file) is not the best way since:

  • you must to apply this in every website you create
  • in case of a sub-theme, you have to copy base theme template.php and merge it in every theme update
  • any filefield module theme related update should be shifted into you code

I think a better (and complete) approach should be a new field display related settings, something like proposed in attached screenshot.

quicksketch’s picture

Status: Needs review » Closed (won't fix)

Sorry, this isn't going to happen. A theme-based solution is the best one in my opinion. FileField has been moved into core for Drupal 8 and won't be changing any more functionality. At least that means that you're safe to override the code in your theme, since it shouldn't change for the lifetime of Drupal 6 or 7.

manuel.adan’s picture

Ok, I'll made this change for my personal drupal base installation. I don't like to do the same work once and once again for every website I made. If somebody wants the patch, just ask me. Thx.

pvanerk’s picture

Adan, can you please send me the patch or indicate where I can download the patch.

Thanks!

rmwolinski’s picture

How can I use "open a File in new window" in drupal 7?

Ganganation’s picture

#24 @rmwolinski
Hope this helps: http://drupal.org/project/extlink

rmwolinski’s picture

I tried this module but this is for external links. Maybe I can't configure it.

jasondecamp’s picture

The solutions given above do not work for Drupal 7 due to changes in the filefield module in core. Use the following code (placed in your template.php file) to accomplish the same as #9 in Drupal 7:

function THEMENAME_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  //open files of particular mime types in new window
  $new_window_mimetypes = array('application/pdf','text/plain');
  if (in_array($file->filemime, $new_window_mimetypes)) {
    $options['attributes']['target'] = '_blank';
  }

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}
pitxels’s picture

#27 is working great :)

aiphes’s picture

#27 works :) for D7 thanks
do you think is it possible to do the same but with the W3C javascript standards ?

onclick="window.open(this.href); return false;" 
petersmeekens’s picture

#27 did it for me too. Thanks!

superdorx’s picture

I inserted code from #27 in my template.php and changed the THEMENAME. My PDFs are still opening in same window. Am I missing something?

rschuetzler’s picture

I'm in the same boat. Not having any luck getting them to open in a new window. It would appear the function isn't being called to create the link. Any hints?

DRIVE’s picture

#27 worked for me as well.... 1 minute and I found it G0ogle.... saved me much time to write from scratch... thanks!

*having trouble with not opening in new links after you insert the code in your theme template? Must flush cache any time you update theme template unless using a mechanism which is clearing it for you (90% of the time you will need to manually flush, so just do that anyway)

sheathe’s picture

Thank you - #27 worked for me in Drupal 7 (after clearing the site cache.)

colorado’s picture

Both #7 and #9 worked for me.

Thanks for sharing this all!!

Chitotakun’s picture

thankful, #7 #9 #27 and #34

Danny Englander’s picture

Though many of the above methods are valid to do this, you could also use JQuery (attribute), I tried this and it works. Obviously your specific code might change a bit depending on what you are targeting. This may not be as comprehensive for some of the methods above but in some cases may be fine. In this example, I had a filefield called "App Landing". This would work for Drupal 6 but could be adapted for 7 as well.

//open docs in new tab or window (pdfs)
Drupal.behaviors.mythemetarget = function (context) {
  if (jQuery().attr) {
$(document).ready(function(){
  $('.field-field-app-landing-files a', context).attr('target', '_blank');
});
}}

Note change "mytheme" to your theme name and refer to # 39 below for instructions how to add this.

colorado’s picture

#highrockmedia -

Where do you put this, JQuery (attribute)?

Danny Englander’s picture

@colorado -- you could do it a few ways.

  1. You could create a "scripts.js" file or whatever you want to call it (and add the customized code snippet as above according to your specific HTML) in your theme folder. I like having a dedicated scripts folder such as "js" or "scripts". Then in your theme's .info file you could call the script like: scripts[] = js/script.js -- make sure to clear your site cache after creating and adding code / files.
  2. use the Drupal add JS method. There are various ways you can do this but commonly done in template.php. This is more for one off things where you might need to just add the script to a single page. If it's something more sitewide, then stick to #1 above. http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_ad...
colorado’s picture

OK then. Thank you very much!

bensoi’s picture

#27 worked for me. thanks a bunch!

if it doesn't work for you, flush the cache. i just replaced the THEMENAME with my own theme name, added some array elements on $new_window_mimetypes, flushed the cache and tadaaaaaah! ^^

mcchrome’s picture

#27 worked just as expected. From an end-user perspective it's a shame the options won't even make it to D8.

4kant’s picture

#27 worked for me - thanks to all of you!

ladybug_3777’s picture

#27 worked the way I wanted. Perfect! Thank you

docker’s picture

#27 solution works fine. Thanks!

ilfelice’s picture

FWIW, #27 works here too (in D7).

thentha18’s picture

Thanks a lot. Tried #27 works perfect on D7.

loko’s picture

Thanks a lot. Tried #27 works perfect on D7.

Me too. Thank you.

tsaks’s picture

Thanks. #27 works in Drupal 7.
Is there anyway to adapt that so that html files that are uploaded can open in a new window?

dvdooren’s picture

I have done as #27 told me. Copied the code into my template.php file, replaced the "THEMENAME" with my actual theme name. After saving, I cleared the cache on my website. But for some reason, this still isn't working.

I have very little knowledge of PHP, so figuring out the problem would be very hard for me. Is there anyone who might know how to solve this?

mcchrome’s picture

#27 still works great.

nitin.k’s picture

#27 Thanks...It works great.

PEP3’s picture

#27 worked perfectly for me in drupal 7... thank you!

konstantinalz’s picture

#27 worked for me in drupal 7. thank you!!!

scott.browne’s picture

27# worked for me. Had to replace the YOURTHEMENAME in the code with mine lol.

Silly I always forget that!

This is a nice feature for ease of use. A lot of requests on websites for this type thing.

Scott
www.coverclubmedia.com

bcobin’s picture

Issue summary: View changes

#27 worked a treat for me... thank you, @jasondecamp - almost three years on!

magendiran’s picture

Thank you - #27 worked for me in Drupal 7 (after clearing the cache)

ladybug_3777’s picture

3 years later and #27 still works for me! Thank you!

hockey2112’s picture

Thanks for #27!

miniwebs2’s picture

#27 works well for document attachments however when using file path links within views, it doesn't appear to do the same thing.
i.e. I have a Title and a File Attachment as Content Type fields
Within my Views settings:
Fields:

  1. Title Field - excluded from Display
  2. File Attachment field - 'Display download path instead of file storage URI " is ticked, as is "Link this field to download the file" and then also Rewrite to the Title Field.

Works perfectly to the pdf it needs to go to but opens in the same window - would very much like it to go to target _blank.

Any thoughts??

FIXED - Sorry - there's a file within views under re-writing for target _blank - works now!

Tsymi’s picture

Thanks for #27 it's worked for me too !

maxplus’s picture

Thanks,

#27 is working for me to.

Other solutions like rewriting the field in views did not give me a solution because I had a multi value field

stevenx’s picture

#27 worked, thx

prsnjtbarman’s picture

#27 - It works fine for me. Thank you.

phanophite’s picture

#27 worked for me as well. Thank you!

thalemn’s picture

#27 works as expected. Thanks!

anou’s picture

Thanks to jasondecamp. Must say: 4 years and #27 still does the trick. ;-)

handkerchief’s picture

Here is my code for drupal 8 if anyone search this.

/**
 * Implements hook_preprocess_HOOK().
 */
function hook_preprocess_file_link(&$variables) {
  // Add target _blank attribute to all file links.
  $file = $variables['file'];
  $url = file_create_url($file->uri->value);
  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file->filename->value;
  }
  else {
    $link_text = $variables['description']->__toString();
  }
  $link = '<a href="' . $url . '" type="' . $file->filemime->value . '" length="' . $file->filesize->value . '" title="' . \Drupal\Component\Utility\Html::escape($file->filename->value) . '" target="_blank">' . \Drupal\Component\Utility\Html::escape($link_text) . '</a>';
  $variables['link']->setGeneratedLink($link);
}
danimanie’s picture

@handkerchief Thanks for drupal 8 hook! It helped a lot.
But there was a little mistake in that line where you set $link variable.
I changed it a little bit to get it working in my theme.
Here is my result:

/**
 * Implements hook_preprocess_HOOK().
*/
function THEME_preprocess_file_link(&$variables) {
  // Add target _blank attribute to all file links.
  $file = $variables['file'];
  $url = file_create_url($file->uri->value);
  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file->filename->value;
  }
  else {
    $link_text = $variables['description']->__toString();
  }
  $link = '<a href="'.$url.'" type="'.$file->filemime->value . '" length="' . $file->filesize->value . '" title="' . \Drupal\Component\Utility\Html::escape($file->filename->value) . '" target="_blank">' . \Drupal\Component\Utility\Html::escape($link_text) . '</a>';
  $variables['link']->setGeneratedLink($link);
}
handkerchief’s picture

@danimanie Thank you for your response, of course, that was my fault, a typical copy paste mistake i guess :) In my productive code i have exactly the same code as you. Thanks for the note and the correction.

Arslan23’s picture

#Danny Englander
Thanks. jQuery work for me in template script.js, But #27 not work with my D7 Theme,i am using zeropoint theme.

Anonymous’s picture

#27 worked for me , thanks .

Adrian83’s picture

For Drupal 8, I copied and pasted #69 into the CUSTOM_THEME.theme file in my custom theme. The only change was to change the "THEME" in function THEME_preprocess_file_link(&$variables) { to my custom theme's name. Clear cache, and all links created by the file field will open in new tab.

Xave54’s picture

#27 doesn't work for me, help!

thalemn’s picture

@Xave54

Which theme are you using? Did you flush all caches?

knalstaaf’s picture

To people who don't get #27 to work: is the mime-type specified of the file you're trying to open in a new window?

By default the following mime-types are mentionned in the code: application/pdf and text/plain - you can find these in the provided code.

Add more of your own if necessary, e.g. for jpg and png files:

$new_window_mimetypes = array('application/pdf','text/plain', 'image/jpeg', 'image/png');

And indeed: flush Drupal's cache aferwards.

grasmash’s picture

april26’s picture

It always amazes me that the tiniest function that is blindly obvious and included in every other CMS as default, requires programming in Drupal. I love Drupal, but sometimes it just requires SO much effort to do something so obvious.

handkerchief’s picture

@april26 You speak right from my soul :)

Taliesin84’s picture

What if I want to apply the #27 workaround to file links of a specific content type? Is it still viable editing the template.php file and adding a similar function?

Won't this workaround make my website a little slower each time a page with a file link is loaded? (noob question, I know)

Abhinaw’s picture

i want to add node url which will open in next tab for eg.

Title :- news
url :- bbcnewse.com/newse (In new tab )

Thanks

Abhinaw’s picture

david.qdoscc’s picture

For D7 this module does the trick: FileField Target

ras-ben’s picture

For Drupal 8, if you want a more readable and Drupal-esque way of solving it, i suggest doing something like this:

It technically results in the same as #69

/**
 * Implements hook_preprocess_file_link().
 *
 * Making sure the file links opens in a new window.
 * This is a bit tricky as we only have access to
 * a generated HTML link in the preproces, so we'll
 * need to generate a new link with our changes and
 * also the standard attributes.
 */
function HOOK_preprocess_file_link(&$variables) {
  if (empty($variables['link']->getGeneratedLink())) {
    // If we dont have a generated link by Drupal standard
    // it knows more than we do, and we can just quit out.
    return;
  }

  $file = $variables['file'];
  $url = file_create_url($file->uri->value);

  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file->filename->value;
  }
  else {
    $link_text = $variables['description']->__toString();
  }

  $link = Url::fromUri($url);

  // All of these options are standard file link, with the exception
  // of target and rel - the two attributes we actually want to add.
  $link_options = array(
    'attributes' => array(
      'type' => $file->filemime->value,
      'length' => $file->filesize->value,
      'title' => \Drupal\Component\Utility\Html::escape($file->filename->value),
      'target' => '_blank',
      'rel' => 'noopener',
    ),
  );
  $link->setOptions($link_options);
  $link_html = Link::fromTextAndUrl(\Drupal\Component\Utility\Html::escape($link_text), $link)->toString();

  $variables['link']->setGeneratedLink($link_html);
}

To the top of your module/template file you'll also need to add:

use Drupal\Core\Url;
use Drupal\Core\Link;
illutek’s picture

#69 worked for me , thanks @danimanie

Kris77’s picture

@qdoscc FileField Target module does not work with "file table" format, but only with "Generic File with Target".

#27 works for me too.

Thanks a lot @jasondecamp.

auxiliaryjoel’s picture

Using Drupal 8, #69 worked for me as per #73 notes

aiphes’s picture

grateful with #69 + #73 for D8. Is it possible to do the same for linkfields ?

Michèle’s picture

#84 works perfect for me (with Drupal 8.7.8). Thank you, @ras-ben!

aiphes’s picture

To #84 :
How do you use your code ? in a module or in the .theme file ? I think it can fix my issue.

Because I encounter an WSOD after updating to D8.8.1 with this watchdog message:
Error : Call to a member function setGeneratedLink() on array dans gasquet_d8_2019_preprocess_file_link() (/home/XXX/www/XX/sited8/themes/custom/THEME/THEME_d8_2019.theme ligne 228)

Line which contain:

/**
 * Implements hook_preprocess_HOOK().
*/
function gasquet_d8_2019_preprocess_file_link(&$variables) {
  // Add target _blank attribute to all file links.
  $file = $variables['file'];
  $url = file_create_url($file->uri->value);
  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file->filename->value;
  }
  else {
    $link_text = $variables['description']->__toString();
  }
  $link = '<a href="'.$url.'" type="'.$file->filemime->value . '" length="' . $file->filesize->value . '" title="' . \Drupal\Component\Utility\Html::escape($file->filename->value) . '" target="_blank">' . \Drupal\Component\Utility\Html::escape($link_text) . '</a>';
  $variables['link']->setGeneratedLink($link);
}

Thanks

watson.sm’s picture

#90

I was running into this issue as well. $variables['link'] is not an object, it's only an array. However, within that array it does have an URL object.

I'm not sure if this is the correct Drupal way of doing things, but I worked around my particular issue with this code:

use Drupal\Core\Url;

function THEME_preprocess_file_link(&$variables) {  
  $linkoptions = $variables['link']['#url']->getOptions();
  $linkoptions['attributes']['target'] = "_blank";
  $variables['link']['#url']->setOptions($linkoptions);
}

I put this code in MYTHEME.theme

Hope this helps.

aiphes’s picture

@#91
I'm testing a module that do the work:https://www.drupal.org/project/issues/file_download_link

So I'll abandon this code way for the moment.