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.
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:
- Create a Views page and add your link field. Set the formatter to “URL, as Link” and exclude from display.
- 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.
- Exclude from display
- Set the html for your image:
<img src="/sites/all/themes/mytheme/images/edit-icon.png"> - In Rewrite Results:
- Check “Output this field as a link”
- 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.)
- In the “Target” textfield, enter “_blank”
- Expand the “More” fieldset and enter a name such as “Edit icon in new tab”.
- 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:
- Don’t add “_blank” for the Target.
- In the “More” fieldset and enter “Edit icon in same tab”.
- Add the “Open in a New Tab” field to the view.
- Choose “Key” as the formatter.
- In the No Results Behavior’s textarea:
- Add the token for the field we set up in #3
- IMPORTANT! - Check the “Count the number 0 as empty” box.
- 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
How To Work Field Collections Into a Legacy Drupal Architecture