I had a task.  It seemed simple enough.  It involved a link field with a title and a url (created by the Link module) and a single on/off checkbox field.  The checkbox was a toggle for whether the link should open in a new browser tab/window.

The task was to create a Views page that displays an edit icon which links to the url and conditionally opens in a new tab/window based on whether the “Open Link in New Tab” field is checked...without using the PHP filter module.

PHP Filters

I went down several paths - Views hooks, Views preprocess functions, template files, template.php, creating a new Link formatter, etc.  There was a nice brick wall waiting at the end of each.  Then I was introduced by co-worker Derek Deraps to an interesting twist in Views. It was all possible using the Views GUI.

The premise is to output a link that opens in a new tab using the Rewritten Results of the “Open Link in New Tab” field and a link that opens in the same tab through the “No Results Behavior” of the “Open Link in New Tab” field. Genius.

Let’s set up an example view to demonstrate:

  1. Create a Views page and add your link field.  Set the formatter to “URL, as Link” and exclude from display.
  2. Add a Global: Custom text field.  This will be our link that opens in a new tab when the “Open in New Tab” checkbox is checked.
    1. Exclude from display
    2. Set the html for your image:
      <img src="/sites/all/themes/mytheme/images/edit-icon.png">
    3. In Rewrite Results:
      1. Check “Output this field as a link”
      2. Enter the Replacement Pattern from your Link field in #1 in the ‘Link path’ textfield.  (The list of available replacement patterns can be found in the first fieldset of the modal.)
      3. In the “Target” textfield, enter “_blank”
    4. Expand the “More” fieldset and enter a name such as “Edit icon in new tab”.
  3. Add a Global: Custom text field.  This will be our link that opens in the same tab when the “Open in New Tab” checkbox is not checked. Repeat all steps in #2 except:
    1. Don’t add “_blank” for the Target.
    2. In the “More” fieldset and enter “Edit icon in same tab”.
  4. Add the “Open in a New Tab” field to the view.  
    1. Choose “Key” as the formatter.
    2. In the No Results Behavior’s textarea:
      1. Add the token for the field we set up in #3
      2. IMPORTANT! - Check the “Count the number 0 as empty” box.
    3. In the Rewrite Results textarea, add the token for the field we set up in #2.

Save the view and view the page. Voila!  The links with the “Open in new tab” box checked will open in a new tab/window.

Additional Resources

Guide to Drupal Terminology

How To Work Field Collections Into a Legacy Drupal Architecture