Drupal 6 Attachment Views
Use multiple-display views to add functionality and value to your site!
J. Ayen Green
BIRMINGHAM - MUMBAI
Download from Wow! eBook <www.wowebook.com>
Drupal 6 Attachment Views Copyright © 2010 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: February 2010
Production Reference: 1180210
Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-849510-80-6 www.packtpub.com
Cover Image by Filippo Sarti (
[email protected])
Download from Wow! eBook <www.wowebook.com>
Credits Author J. Ayen Green Reviewers Lena Doppel
Editorial Team Leader Gagandeep Singh Project Team Leader Lata Basantani
Dave Myburgh Project Coordinator Acquisition Editor
Poorvi Nair
Usha Iyer Proofreader Development Editor
Lesley Harrison
Dhiraj Chandiramani Graphics Technical Editor
Nilesh R. Mohite
Neha Damle Production Coordinator Indexer Rekha Nair
Shradha Vichare Dolly Dasilva Cover Work Shradha Vichare
Download from Wow! eBook <www.wowebook.com>
About the Author J. Ayen Green is a software and website developer, writer, and poet. He is the
chief software designer at Ayen Designs. He and his wife, Sofía-Aileen, make their home in New York City. This was my second title for Packt, and was as enjoyable an experience as the first. That isn't coincidental, and I'd like to thank those responsible for the smooth ride: Usha Iyer, my acquisition editor, who has a keen eye for talent and a sharp sense of humor; Lata Basantani, projects team leader; Poorvi Nair, project coordinator, who is always warm and gracious, even when cracking the whip; Dhiraj Chandiramani, my development editor, Neha Damle, my technical editor, who is very adept at turning a mound of manuscript into what you're holding, and Patricia Weir, who always brings a smile to my face, and the rest of the Packt team, Rekha Nair, Gagandeep Singh, Lata Basantani, Lesley Harrison, Nilesh Mohite, Dolly Dasilva and Shradha Vichare, all of whom combined to create a beautiful publication. Constructively critiquing another's work is always a challenge, and my technical reviewers, Dave M and Lena Doppel were definitely up to it. Whatever I may think of my writing ability, I'm certain that your experience was the better for their efforts. This website used in this book was a live site, GuildBuildersInc. com, and its development occurred in parallel with the writing (not for the faint of heart). Many thanks to Scott Corley, its president, for sponsoring a fun project, being flexible regarding the design and timing (one usually doesn't measure website development in chapters), and for not changing the specs along the way—well, not too often.
Download from Wow! eBook <www.wowebook.com>
My wife, Sofia-Aileen, once again, handled this project with the minimum of grumbling, despite our usually being two ships passing in the night. You're always there to give me a reason to get up in the morning—beyond brewing coffee for you. Finally, I must not fail to mention those who provided the foundation for this book. My thanks to Dries Buytaert, for his gift (and that of some of the world's best coders) of bringing Drupal to the world. Equal thanks go to Earl Miles, aka merlinofchaos, for his spectacular creation known as Views. And to the countless denizens of #drupal, #drupal-support, and the Drupal lists, especially Kenn_ VM, who are always willing to give advice, empathy and/or a laugh.
Download from Wow! eBook <www.wowebook.com>
About the Reviewers Lena Doppel studied organizational development, computer science and web design. Currently she is working as a university lecturer, consultant, and web developer.
She is teaching media technology and web design at the University for Applied Arts, Vienna and is co-owner of 'cat-x media' providing Web and Drupal services for small companies, artists, museums, and exhibitions. When time allows she also blogs a little on her own website lenadoppel.com. I would like to thank Florian Prix for calling me his favorite girl geek, the Drupal community for just being there and Drupal for growing up the way it does.
Dave Myburgh has been involved with computers since before the web existed.
He studied as a molecular biologist, but discovered that he liked working with computers more than bacteria. He had his own computer business in South Africa (where he grew up) doing technical support and sales. He even created a few static websites for clients during that time. After moving to Canada, he got sucked into the world of Drupal a few years ago, when a friend wanted a site for a local historical society. Since then he has once again started his own company and now builds websites exclusively in Drupal (he doesn't "do static" anymore). There is no lack of work in the Drupal world and he now balances his time between work and family. He has reviewed several Drupal books including Drupal 5 Themes and Drupal 6 Themes. I would like to thank my family for being so supportive of me and what I do. Working from home can be a mixed blessing sometimes, but having the opportunity to watch my son grow up makes it all worthwhile.
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>
This book is dedicated to my cousin Gerry. Aside from teaching me to play poker, stick ball, and the trumpet, and taking me on one of the most memorable joyrides I've ever been on, he is one of those rare people who is always there, and in so being tends to make things better.
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>
Table of Contents
1 7
7 9 11 12 20 23 27
29
57
30 32 33 41 48 48 56 58 62 65 66 71 73 73 78
Download from Wow! eBook <www.wowebook.com>
Table of Contents
79
80 86 94 96 106
107
139
107 111 115 124 130 137 139
159 168 172
173 174 175 184 185 190 196 199
201
219
202 206 206 210 211 216 218 219 222
[ ii ]
Download from Wow! eBook <www.wowebook.com>
Table of Contents
226 228 234 238
239
251
239 240 240 241 242 242 243 243 244 245 245 245 246 246 246 247 247 248 248 249 249 249 250 250 250
252 256 256 256 257 257 257 258 258
[ iii ]
Download from Wow! eBook <www.wowebook.com>
Table of Contents
258 259 261 262 262 263 263 264
265
271
265 266 266 266 267 269
[ iv ]
Download from Wow! eBook <www.wowebook.com>
Preface This hands-on tutorial will teach Drupal developers across the experience spectrum how to use Attachment displays to make a quantum leap in View functionality and added-value to users. This book starts by introducing Attachment Views as reader activities. Here, we create a single Attachment View and take a closer look at giving each page an interactive feel. It also shows you how to create a View containing an Attachment View. Later, using practical examples, you will learn how to develop a 3-view composite display using two and three custom content types. You will also develop a composite display using multiple Attachment Views; to provide a control panel of sorts from which you can view the various content types. Finally, we will put the home page together making use of Views, blocks, a flash slide show, and other pieces.
What this book covers
Chapter 1, Something Old, Something New, contrasts the capabilities of a standard Drupal website to what will be achieved in the book, and in so doing, the rationale for the book is presented. Chapter 2, Attachment Views—A New Beginning, introduces Attachment Views as reader activities. Each View created would be able to stand alone, but will then have a single Attachment View created to give each page an interactive feel. Chapter 3, Interactive Page Regions, continues with single Attachment Views. In addition to creating another view and Attachment View, a small module will be created to provide the e-mail functionality needed for contact. Chapter 4, Additional Displays, helps the reader to create a view with an Attachment View, a Block display, and an additional Page display.
Download from Wow! eBook <www.wowebook.com>
Preface
Chapter 5, Bios, will have the reader develop another 3-view composite display, using two custom content types. Chapter 6, Prior Jobs, will take the reader through another 3-view composite display, using two content types: jobs and bios, and the templates necessary to format it, with one of the attachment views being purely for display. The page will display prior jobs for the reader to select from, and once selected, a separate part of the page will display the job info and the appropriate bio. Chapter 7, A Different About-Us, we will develop a 3-view composite display using three custom content types. On most websites, this is a static, fairly uninspired page. Here, we will create a composite page so that the bios and prior jobs will be shown and selectable in addition to the company information that will be in a separate piece of content. Cascading View templates will be used for formatting the overall view. Chapter 8, Control Panel, develops a composite display using multiple Attachment Views, to provide a control panel of sorts from which management can view the various content types. Chapter 9, Front (Home) Page, puts together the home page; making use of Views, blocks, and other pieces. Chapter 10, Punch List, addresses the final tasks, such as defining roles, users and permissions, site configuration items, and more. Appendix A, Add-On Modules, contains information about a few modules that were used in the site and not in the book. Appendix B, Custom Content Types, presents introductory information regarding the creation of a content type followed by information about each type that was created for the site.
What you need for this book Drupal version 6.
Who this book is for
This guide is aimed at Drupal developers of any level, who have not yet explored this functionality.
[2]
Download from Wow! eBook <www.wowebook.com>
Preface
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "We can include other contexts through the use of the include directive." A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "clicking the Next button moves you to the next screen". Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
[3]
Download from Wow! eBook <www.wowebook.com>
Preface
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to
[email protected], and mention the book title via the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@ packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code for the book Visit http://www.packtpub.com/files/code/0806_Code.zip to directly download the example code. The downloadable files contain instructions on how to use them.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www. packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
[4]
Download from Wow! eBook <www.wowebook.com>
Preface
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at
[email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at
[email protected] if you are having a problem with any aspect of the book, and we will do our best to address it.
[5]
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>
Something Old, Something New If you have developed Drupal websites before, you already know that you can only get so far in developing a site before you run into the need for Views. The first part of this chapter describes views, what they are typically used for, and how we will take their use to the next level. If you are already familiar with views, feel free to skim this chapter. The remainder of the chapter will be used to describe our project site, its underlying need, and how we will fulfill it.
Content management systems
A straight-forward case for a content management system is an online magazine, a website that will contain articles. They will be written by various authors on various topics. So, we have a framework that allows us to store and edit the articles. We also have a front (home) page on which we show 'teasers', excerpts of the articles. The articles are shown based on which was most recently published. We can specify that an article is published (available for viewing), and that it can be selected by the framework to show on the front page. We can also specify that an article should remain on the front page until we remove it, which is known as making it 'sticky'.
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
Let's take a look at the Drupal CMS in action. Drupal is the brainchild of Dries Buytaert, and is a shining example of what can be achieved with an Open Source project. I have created a fresh installation, named the site, and added two articles.
We can see that the CMS has lived up to it's promise (implied by the virtue of being a CMS), and we have a nice, clean layout, our two articles as teasers, well-positioned, and links (Read more) to pages containing the full text of each. The system works very well, and can provide a functional site with very little effort beyond installation and configuration. So, our magazine begins to accumulate enough content for us to want to have 'departments', each focusing on specific topics, or categories. With that done, we want a page for each department. The first of these will be 'Travel'. Great! Just a couple of points: How do we do what the front page is doing, on another page? Having that page how do we show only articles that are about travel? We can mark the articles as being about travel through the use of taxonomy terms, but how do we specify that we want to display only articles so marked? The short answer is, we can't. Not with Drupal right out-of-the-box.
[8]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
However, if that were the final answer, this would be a very short book. The fact is that many great ideas and decisions go into the making of Drupal. One of these was to make the install package as 'light' as possible. In other words, instead of bogging down the installation with tons of options that may or may not be used, have them available as add-on modules.
Creating a taxonomy vocabulary
First, we will create a vocabulary that will contain our department names. We'll set it so that its entries are created as tags when creating the article (Story). In the following images, we'll create a vocabulary and see the resulting screen that shows it.
The create vocabulary is now available for the addition of terms.
[9]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
With our vocabulary created, we'll edit our travel article.
We will also add a tag to it, which we'll later use to identify this as a travel article.
We can see an immediate change on the front page, as a result of assigning a taxonomy term to our article.
[ 10 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
The taxonomy term is included in the display of our article teaser. All the pieces are in place and ready for us to create our View.
Views
Enter Earl Miles, also known as merlinofchaos within the Drupal community. There is a 'trinity' of modules available for Drupal that offer an amazing leap in functionality (he wrote two of them), and Views is one of those modules. A view is originally a relational database term, referring to a temporary arrangement of information in the database so that it can be presented in a meaningful way which is different than the underlying table layout. The Views module accomplishes the same thing, and provides the glue to tie itself in to the rest of Drupal and, especially, the ability to theme the result with templates. In other words, it gives you the ability to look at Drupal content in a way you would otherwise be unable to (without custom code). So, for example, our magazine can create a View that allows us to view content as we do on the front page, but with the selection of that content filtered in a way that we define, which in this case would be by department. In fact, let's do that.
[ 11 ]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
Creating a View
In order to create a View, the Views module needs to be installed. Ours already is, and the details for that are given in Appendix A. We'll navigate to the Views page. Via the menu, it would be Admin | Site Building | Views. We'll use the URL, which is admin/build/views.
[ 12 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
The idea behind a View is to control the building of an SQL statement, in order to retrieve only the rows that we want. In this case, the rows will be nodes, which is why we created a 'Node View'. The following image shows the sections of the Views panel labeled as they relate to an SQL statement.
We want to select only the nodes that have the taxonomy entry of the department we want, which in this case will be travel. There are three ways we can accomplish this: 1. Filter: We can specify a selection filter (equivalent to an SQL 'where' condition) requiring the taxonomy term to be equal to 'department'. 2. Exposed Filter: The same as the Filter option, but exposing the filter to the user so that the value can be changed. 3. Argument: An argument also creates an SQL 'where' condition, but can be set externally to the View and passed in the URL. We're going to select the argument method. The reason is that in accepting an argument that defines the taxonomy term instead of specifying it in the View, we can create a page capable of showing any department. How will we get the argument passed? Simple. We'll get to that once we create the View. There are two filters that we do want to create. Even though we'll be accepting the taxonomy term as an argument, we still want to make sure that we're only selecting Story nodes and that the nodes are marked as published. Let's create the filters.
[ 13 ]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
1. The filter selection is grouped by the source of data. We want the Node items, and we'll check the boxes for Node: Published and Node: Type.
2. When we add the filters, we will receive a settings window for each filter. In
the Node: Published settings, we're simply specifying that the node needs to be published.
[ 14 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
3. In the Node: Type settings, we are offered the existing content types from
which to choose. We want to select Story nodes only.
4. We'll define a sort next. With this View, we can define our requirements in
any order. That's not always the case. For example, if we were going to use a relationship, it would need to be defined before we could select any fields using it.
[ 15 ]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
5. We want the travel articles to appear in the order of most-recent to oldest. We could select Node: Published date as our sort, but if an article is subsequently re-edited, the published date won't change, but we want it to move to the top of the list. So, instead, we'll use Updated date.
6. In the settings window we'll choose Descending, because we want the most recent date first.
[ 16 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
7. We'll define our argument next.
8. We're going to request a department by passing the ID of the department's taxonomy term (tid). We'll go into more detail about that when we finish defining our view. For now, let's select Taxonomy ID from the argument list. There are several choices that look similar, so be careful.
[ 17 ]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
9. For its settings, we'll leave everything as it is. We are then specifying, by default, that if no argument is passed, all department articles will be presented, and if a department is requested that does not exist, a 404 page will be given. In our current context we don't really care about the handling, because we will be controlling what is requested. The one caveat would be if a taxonomy term was removed, but the menu choice for that department was not.
[ 18 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
10. Right now, the View is expecting that we will select individual fields to display (the SQL 'where' arguments). We have another choice, which is to have the node selected, and that is what we want to do.
11. We want to show teaser articles on the department page, as opposed to the entire article, so we'll make that setting.
[ 19 ]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
12. At this point the View, in terms of the SQL component, is fully defined. We can scroll down to the Live Preview section.
Narrowing the selection
1. We see that we have article teasers showing, with links to view the entire article (the article title is one, and the Read more is another). Wait! Wasn't the whole idea to show the articles for only the travel department? What is the Taming the Shrew article doing here? We haven't provided an argument to our preview, and if you remember, when no argument is present, the behavior we defined is to show all articles. Let's supply an argument. We need to have the tid of the taxonomy term in order to use it as an argument. If we hover the mouse cursor over the term travel, and look at the link URL in the bottom of our browser window, we can see what the tid is.
[ 20 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
2. We can now enter the tid into our Live Preview window and see
what happens.
[ 21 ]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
3. Now we just have the travel article teaser. If we scroll down a little further, we can see the underlying SQL query that was generated based on our settings.
4. The only thing left to do in the View itself is to define a path to access it. As strange as it may seem, at this point there is nothing to access. We have not actually defined a display entity for this View. In other words, right now there is no output we can access from outside the View edit. We need to create a display. If you look at the top left of the View panel, above the Add Display button, you see that Page is the current choice, which is the one we want. Another choice in the drop-down list is Attachment, which is what this book is about. We'll start using that choice in Chapter 2, Attachment Views—A New Beginning.
5. For now, we'll click the Add display button.
[ 22 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
6. We want to create a path, which is set to None right now.
7. We'll name the path "displays".
8. We can now save the View. The only thing left to do is create a way to invoke it.
Creating the menu choice
1. We set out to be able to display articles for the travel department, and at this point, that is the only taxonomy term that we've defined. We need to edit our menu and add a choice. The menu editor is at Admin | Site Building | Menus (admin/build/menu) and from there, we want to select the Navigation menu to edit.
[ 23 ]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
2. We want to add a menu choice to this menu.
3. The important setting here is the Path, which we'll set to departments/1. This serves to invoke the departments path, which is the path alias to which we assigned our View, and also to pass the argument 1 to the View, which is the tid of our travel department.
4. We'll navigate back to the home page, and select our new Travel Department menu choice.
[ 24 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
This is an example of what a View can do for us. We can create further menu choices for various departments too. This is fine for showing all the articles for our Travel department. However, what if we want our department page to provide the user a list of articles from which to select an article to view? We could define our View to present fields, instead of nodes, and then the page would show a list of titles, but the page would name when the user selected a title, and they would have to click the Back button, or some such, to return to the list and choose another title. What if we want the list and the article to appear on the same page? Two separate areas communicating with each other? That is the secret of Attachment Views, and we will begin looking at them in Chapter 2. Here, we have one more thing to do, and that is to present our project site.
The project site During the course of this book, we will be creating a website. The website is part of an actual project, and the development is live and occurring in parallel with the writing of the book. With this chapter actually being written last—because it's declarative about the direction of the book, and it's always easier to do that in hindsight—I can say now that I wouldn't recommend this approach when the site is for a client. Minds change, business needs change, things get delayed (but deadlines don't), it can make things messy! That said, it hasn't been too bad, but be forewarned! The website is for Guild Builders, Inc. of Rancocas, New Jersey, a commercial construction firm. The site will be their first web presence. It will serve as an initial point of sales information for clients, and a primary point for initial information about opportunities for subcontractors interested in providing services.
[ 25 ]
Download from Wow! eBook <www.wowebook.com>
Something Old,Something New
The business functions to be addressed (and the resulting pages, in parentheses) are: •
A 'landing' area (home page)
•
A way to contact the company (contact page)
•
Sign-up capability for subcontractors (subcontractor registration and profile)
•
Information about jobs open to bid (jobs page)
•
Biographical information about Guild Builders staff (bios page)
•
Examples of prior projects (prior-work page)
•
Company information (about us page)
•
An easy way for management to view the above (control panel)
These would seem to be independent, as pages on a static site. However, we're going to kick it up a notch. If we look more closely, we can see that many of these are related: Prior Work to Bios (the project manager), Subcontractors to Jobs, About Us to Prior Work, and so on. What we're going to do throughout the book is use Attachment displays (I'll be using that term synonymously with Attachment views) liberally to provide a visual and structural linkage between the functions on the same page. So, for example, when we choose an example of Prior Work, we will be presented information about the job and information about the project manager all on the same page! The project site uses the current version of Drupal 6 (6.13 at the time of this writing... oops...make that 6.14...don't blink) and several add-on modules. The details of the modules and their configuration are given in Appendix A. We are also going to use a handful of custom content types too. Story and Page are the installed content types of Drupal. We have created some that contain fields suited for the type of content they are. The details of these are given in Appendix B. It's time for you to move on to Chapter 2, and time for me to write the appendices!
[ 26 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 1
Summary
In this chapter, we learned what Views are, and what a standard View can provide to us in functionality that Drupal, as freshly installed, cannot. We also learned what the project site will be, and how we can deliver its requirements through the use of Views, and in particular, Attachment Views. In Chapter 2, we will be creating the first View for our project site and our first Attachment display for a View as well.
[ 27 ]
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>
Attachment Views–A New Beginning Looking at just about anything worth doing, a question will often arise beginning with the words, "How do I." Often the challenge can seem daunting. Then, one finally intuits, discovers or otherwise stumbles upon the answer and simultaneously is offered several alternative opinions, each being offered as the best way to accomplish the same goal. This is the case whether planning a vacation route, taking a photograph, or creating part or all of an application. There are a number of ways to accomplish what we will be doing in the chapter. If you spend any time on the Drupal IRC (Internet Relay Chat) channels, you will most likely receive varying opinions as to the best approach and, perhaps, come away more confused than when you started. Sometimes, there is no clear answer. One approach would be to write custom code. Another might be to use the Panels module. Each approach is valid, and has different pros and cons in terms of features, effort, learning curve, and time. Here, we're going to face each challenge in the same way, with attachment views, which means less coding, less time, and a smaller learning curve.
Download from Wow! eBook <www.wowebook.com>
Attachment Views – A New Beginning
Here's what we'll do in this chapter: •
Learn what an Attachment view is
•
Learn what you can do with an Attachment view
•
Consider in what situations an Attachment view can be useful
•
Cover basic view theming
•
Create a Page view
•
Create an Attachment view
•
Theme the view
What is an Attachment view?
What is a view? We created one in the previous chapter. If you skipped that chapter, or if you're still a little fuzzy on just what a view is, consider (re)reading Chapter 1, but here is a summary. A view is the dynamic display of one or more pieces of related content based on one or more criterion.
What does that mean in practice? Let's consider a simple example. Let's say we have created a number of nodes of the content type 'Story' and assign one or more taxonomy terms to each. Having done that, we want to be presented with a list of teasers for each Story that has 'travel' as one of its taxonomy terms. It's a fairly common requirement. If you're familiar with Joomla!, for example, it could be accomplished by means of a Section or Category Blog page. The fact, though, is that the architecture that makes Drupal so extensible results in there being no manner in which to accomplish this using a core module. Enter the Views module, which will allow us to specify that we want a page on which we want to view x number of nodes, their selection based on certain criteria, which in this case will be nodes containing the taxonomy term 'travel'.
[ 30 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 2
That, in a nutshell, describes views at their simplest. Now, how about Attachment views? Well, to continue using the same example, let's say that our requirement has changed, and we don't always want a page based on every node having to do with travel, but want to be able to select destinations from a list of regions shown on the same page, as illustrated in the following figure. DESTINATION Africa Asia Australia Carribean Island Europe North America Pasific Island South America
Cebu
Hong Kong
Bangkok
Osaka
Chennai
The box on the left shows the available travel regions, each of which is a taxonomy term, with Asia having been chosen. The boxes on the right are node teasers, each of which has Asia among its taxonomy terms. How can we accomplish this? One method would be to code a custom page in PHP and display it. That would work, but it would also set the page in stone to some extent, bypassing the flexibility that Drupal provides. We could also create a menu of destination regions and put it in the sidebar as a block. That would work too, but the menu would not be dynamic, and would have to be edited each time a region was added, changed, or removed. One further option would be to have two separate views. How can we have two views though? We could create one as a block, but let's say that the design calls for the selection choices to be in the content area of the page. So, that means we need to find a way to have both views as content. Enter Attachment views.
[ 31 ]
Download from Wow! eBook <www.wowebook.com>
Attachment Views – A New Beginning
Reviewing the view requirements
The business for which our website is being built is a commercial builder's. As with most construction businesses, subcontractors represent the major source of labor. On this site, Subcontractors will be the user type that will need to register, in order to subsequently review jobs and bid for them. There will be other authenticated user types, such as management, job supervisors and admin, but they will have user records created for them and will not need to register. Customers will be anonymous users.
To that end, a custom profile has been created for subcontractors, to capture the necessary information. We're using the content_profile module (see Appendix A) so that each subcontractor profile will be a node. We are going to have a menu from which the user will select a contractor for which the details will be displayed. For a given view, we can create various displays. A view to be displayed like a node will have a Page display—'Page' can be thought of as a web page—and one that is to be displayed as a block will have a Block display.
[ 32 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 2
Considering our menu of subcontractors, and the display of a subcontractor's details, in conjunction with the terms 'Page display' and 'Attachment display', the reasonable inference is that the Attachment view will be the menu-style list of subcontractors, and the Page display will be the subcontractor details, the page being larger than an attachment, and the details being larger than the menu. However, that's not necessarily the case, and in subsequent examples we'll invert that assignment of content to display. The description of the subcontractor list may bring the thought 'Block' to mind. Often a block can be used in place of an Attachment display, and in fact, the option to create a Block display in the view is just one selection away from the Attachment type. We're using Attachment displays rather than Block displays because Attachments are not as entity-like in their construction, and are easier to place anywhere within the page content than Blocks, which are more easily placed in regions adjacent to the content area. Attachment views do not include paging as do Page views. We are only going to be showing one subcontractor's details at a time, so there is no paging issue there. However, when we list the subcontractors to select from, there could be dozens, or even hundreds, and that will require us to have paging available for that display, so the Page display for our view will be the subcontractor list. We'll build that first.
Activity 2-1–Subcontractor page view
The Subcontractor page will allow the user to view the details of a subcontractor chosen from a dynamic list. That is, the list of subcontractors will not be something separate that requires editing whenever a subcontractor is added or removed, and the list will be in the content area of the page and not in a navigational menu.
[ 33 ]
Download from Wow! eBook <www.wowebook.com>
Attachment Views – A New Beginning
1. Let's create a new view. We're going to create a node view named subs, as shown in the following screenshot:
2. Click Next and the Views panel is presented. The panel will allow us to customize the view settings. We'll start by creating a Page display for the view. The Views page will always attempt to provide you with a real-time preview based on your settings. Often, the settings are being established in an order that is not conducive to creating the preview, because some information is missing. In that event, you will see a pink warning about this, for example, Fields is the display type but no fields have been chosen. Use the warnings as a way to tweak your memory about what you have left to do, but don't worry about them, as long as there are none remaining when you think you're done. [ 34 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 2
3.
We'll click on Title and change the view title, as shown in the following screenshot. Click Update default display when you are finished.
4. Let's look at some of the other configuration options in Basic Settings. Leave the style settings as it is. A style plugin isn't needed, because the view will eventually be themed, and since it will only be showing one record it doesn't require a table or grid. We'll also leave the Row style set as Fields, as we want the profile data to be displayed as a vertical list of fields. Again, changes can be made when the view is themed. We won't use AJAX at this time. We do want to use paging with this display. It's likely that the subcontractor list will be large, and so we'll only want a small amount being shown at one time. We'll change the Use pager setting to "yes", and from the config options choose Mini pager.
[ 35 ]
Download from Wow! eBook <www.wowebook.com>
Attachment Views – A New Beginning
5. Leave the More link setting at no, we don't need a More link, and likewise, since each record is a separate subcontractor node, we're not concerned about unique records. 6. As this view is meant only for use by the management of Guild Builders, we'll want to restrict access to it. Change the Access setting to restrict access to a specific role.
A role called management has already been created for use by the management staff of Guild Builders. There will probably be more roles added later, such as one for staff and another for the subcontractors themselves. 7. We'll assign access to the management role.
We won't be caching the view, nor exposing the form in a block, so we'll leave the settings caching at one and expose form in block at no. There will be a page header and footer, but they can be added later. Empty text won't be an issue, because the node selection will come from a list based on existing nodes. That takes us to the end of the Basic Settings pane. Let's move on to Sort criteria. 1. We want the subcontractors to be shown in alphabetical order, so sort on Node title, which is the subcontractor name.
[ 36 ]
Download from Wow! eBook <www.wowebook.com>
Chapter 2
The sort order will be set to ascending.
[ 37 ]
Download from Wow! eBook <www.wowebook.com>
Attachment Views – A New Beginning
2. Next, we will look to the Filters pane. We only want to select Subcontractor nodes (described in Appendix B), so filter based on node type.
3. We need something to be shown in this view display, so select Node: Title in the Fields settings.
[ 38 ]
Chapter 2
4. In the subsequent dialog, specify that the value of the field will be output as a link, and point that link at the view path, with the contractor being used as ID. We'll use subs/ as part of the path for two reasons: to associate the content with the subs content type, and to make it easier to identify the intent of the path if we ever need to write module code to act based on the path. That is, the path makes it easy for the code to identify it as being subcontractor content.
[ 39 ]
Attachment Views – A New Beginning
5. The final thing to do in this display is to define the path.
6. With our view display complete, save it, and then test it. First, we'll run a quick check on it to make sure there aren't any configuration errors, by clicking the Analyze button.
The View analysis returns good news.
7. With no errors discernible, we're ready to preview. Looking at the Live preview section, we might already see preview output from our view, but we want to ensure that the expected output will appear for the Page display. But the preview normally shows the default display output unless changed.
[ 40 ]
Chapter 2
We'll need to theme this display later, so that it appears where we want it to on the page, but it's fine for now. We had created two test subcontractor records in advance, and both are listed. There's no sense clicking the links at this point, since what we need them to load is the display we're about to create. Next!
Activity 2-2–Subcontractor Attachment view
1. Let us begin by creating the Attachment display for our current view.
Remember to click the Override button when changing any settings for this display, so that they are only applied to this display and not the others!
2. In the Basic Settings pane, the only change to make is to set Items to display to 1, as we will be showing only one subcontractor record at a time.
[ 41 ]
Attachment Views – A New Beginning
3. Move on to the Arguments pane. We want to be able to supply this display with an argument, so that it will show us a specific subcontractor profile. Click on the + icon, and scroll down through the field list to add Node: Title. Remember, we're using the content_profile module, so each subcontractor profile will be a node.
Titles in custom content types In our custom content type, subcontractor, the label of the title field of the node creation form was changed from Title to Company. However, that doesn't change the internal field name, so when using that field as an argument or filter in a view, the field will still be selected as Node: Title.
The way an argument works is that it is appended to the URL when requesting the page. So, for example, the URL for our view, when live, will be http://guildbuildersinc.com/subs. To request the view showing the subcontractor Acme, the URL would be http://guildbuildersinc. com/subs/acme. Drupal will separate the argument from the rest of the URL, and pass it to the view processor as an argument array, $args. Key 0 of that array will be the argument count, and key 1 will be acme. This way, the view subs will know that it was called with the argument 'acme.'
[ 42 ]
Chapter 2
4. Adding the argument brings up a subsequent dialog. We want the title of the view to show as the subcontractor company name. Since that is the first (and only) argument, and thus is in position 1 in our argument list, put '%1' in the Title field to indicate that argument 1 will be used as the title. Remember, argument 0 is always a value indicating how many arguments are present in the URL. The first true argument in the second position, but we count from 0. So, for example, if our view took two arguments, first and last name, Joe Smith, the array received in the view would contain a 2 in array subscript 0, indicating two arguments are present. Subscript 1 would contain Joe, and subscript 2 would contain Smith. Specify that an empty page be displayed if either the argument is omitted or does not validate. Check the transform spaces to dashes in URL box, so that when the page URL is produced Acme Contracting becomes acme-contracting instead of the acme%20contracting we'd see if spaces remained in the name.
[ 43 ]
Attachment Views – A New Beginning
5. We had left the Row style as Fields, and now we need to identify which fields we want. Click the + in the Fields pane, and then check the boxes of the fields we want. Select all the Content fields (these are the custom CCK fields created for the Subcontractor content type—see Appendix B), as well as the user e-mail field. 6. We're asked whether we want to change the way the field data is handled. For most fields we won't want to make any changes, so just click Update for each one.
[ 44 ]
Chapter 2
7. We have a website field (field_website), which gives the URL for the subcontractor's website. Set this field to be displayed as a link, and enter a token, from the list of tokens presented, to use this field's contents for the link destination.
8. Next, we'll move on to the Attachment settings pane that we need to change, which is the Attachment settings pane. Specify that our Attachment display should be attached to the Page display.
[ 45 ]
Attachment Views – A New Beginning
The last thing we'll do to this display is reorder the fields. Right now they're in the same order that they were in when we checked the boxes, which is not the order in which we want them displayed. Click the up/down arrow icon next to Fields, and drag each field into the position we want, and then click Update.
9. That completes the construction of our primary view. In the following screenshot, we can see the changes we made reflected in the view summary pane.
[ 46 ]
Chapter 2
10. We're ready to preview the view and make sure the display is what we're expecting. First, enter the name of the test subcontractor into the preview argument field and make sure the Page display is selected.
11. Lastly, enter the URL into our browser and check the view with the theme.
[ 47 ]
Attachment Views – A New Beginning
Theming the subcontractor view
By looking at the previous screenshot, it is apparent that the presentation is far from being user-friendly. The list of subcontractors and the subcontractor details appear to be one large list, and this is with only two subcontractors in the list. Add a few more and the details will be pushed right off the visible page. We'll need to improve on this, and we can do it by theming our View. The thought of theming gives many people the shakes. While it is certainly a complex topic, we don't need to consume it in its entirety. Let's just work with small pieces for now. We'll do more theming throughout the book.
The makeup of a theme
A full theme is basically a combination of some or all of the following: •
One or more template files
•
A CSS file, or several
•
A set of functions
•
Supporting files
We won't be creating a full theme. We will just be adjusting the existing view theme somewhat. We need to simply create one template file, not even from scratch, and a few entries in one of our theme's CSS files.
Selecting a template file One of the most confusing aspects of theming to most people is the selection of (and naming of) the appropriate template file. I'll try and remove some of the mystery and headache for you. There are essentially four layers of output in our Node View. The specifics will vary based on selections made when defining the View, such as whether the style is Rows, Table, Grid, and so on. Let's focus on this view, but keep in mind that some of the following information will vary in subsequent views: 1. Fields: Things such as the subcontractor name, phone number, and so on. 2. Rows: Each node can be displayed as a 'row' of one or more fields.
[ 48 ]
Chapter 2
3. Styles: The output prior to styling being applied to it. 4. Display: The complete view, already formatted in sections, such as the Attachment, Page, Pager, More link, and so on. In deciding a name for the template file, the first step is to identify at what point we need to 'interrupt' the process and insert our requirements. We need to alter the formatting of one field, but only one, and we will do that via CSS. We don't need a template file for that. So, what do we need a template file for? We have two displays: the Page display containing the subcontractor list and the Attachment display containing the subcontractor details. We need to separate the two displays. The format of each display is acceptable as it is. That is, we don't want to change the way either display looks, we just want to take each en masse, as if it were a block, and affect its positioning in relation to the other. So, we can rule out the Field-layer templates, because we're not doing any formatting at the field layer. Likewise, we can eliminate Row-layer templates. Since we're not concerned with restyling the content of our displays, we will have no need for a Style-layer template. That leaves the Display-layer, and that is what we'll need. Note that you can select more than one template layer. For our current need, we're only working with one layer, but depending on the needs at the time, there could be one or more template files needed for one or more layer. So, we've decided we need a Display-layer template file. What do we do next? Well, here, the View panel can assist us. If we look at the bottom of the Basic settings pane, we will see Theme: Information. Normally, I'd recommend that you make certain you've selected the correct display before clicking the Information link, because the theme information is usually relevant to a specific display, but since we're going to be working at the View level, and not within a certain display, the current display is not a concern.
[ 49 ]
Attachment Views – A New Beginning
On clicking the Information link, we are presented with the information shown in the following screenshot.
This is usually where people's eyes start to cross or glaze over, followed by the shaking. First, look at the highlighted paragraph headings (which will be blue on your screen). The first is related to Display-layer theming, then Style-layer theming, Row-layer, and then a paragraph for each field in the Field-layer, with the Node Title field (the field that contains our subcontractor name) being the first in the list. At this point we're only concerned with the first paragraph, Display output. Following that highlighted identification in each paragraph is a series of template file names. If you have not done any theming with the View, the first will probably be bold. The bold filename indicates which file will currently be used to theme that layer. The filenames progress in each paragraph from the least specific to the most specific. That is, in looking for the first time at the initial paragraph, the first file is views-view-tpl.php. This file affects every view in your website. If you were to create your own version of the file and put it in your theme directory, it would then affect every field in every view displayed using that theme. [ 50 ]
Chapter 2
Now look at the highlighted filename in that paragraph: views-view-Subs-attachment-1.tpl.php. Wow! That's a long one, though the file-layer names are even longer. Ok, let's break it down and clear and uncross those eyes: •
views: This template is being used with a view
•
view: This template affects views at the individual view level
•
Subs: This template affects only the Subs view that we created
•
attachment: This template affects only the attachment display of the Subs view
•
This template affects only the first attachment display of the Subs view
We're going to create a template file that will affect the Subs view, and therefore, the name will be views-view—Subs.tpl.php. How do we create it? The good news is that we do not have to create the file from scratch. There are example files that we can modify, rename, and save to our theme. The location of these files is in the views module directory, which, depending on your site, will either be located at sites/all/modules/views/theme/ or modules/views/theme/. The following screenshot shows a list of the files available there to be copied.
[ 51 ]
Attachment Views – A New Beginning
We will choose the file that is listed first in the Theme: Information paragraph that represents the layer we're working with. That will be views-view.tpl.php. Let's get to it!
Activity 2-3–Creating the view template file Inside the file, we look for mention of attachments and rows, which is the data we need to separate, and find the following:
The variable $rows contains the contents of our Page display. $attachment_before or $attachment_after contains the output of our Attachment display, in this case, $attachment_after. What is happening here, with each set of .
[ 52 ]
Chapter 2
We want to separate the Page display and Attachment display. If we leave the template as it is, Attachment displays with a position of Before will appear before the Page display, and those with a position of After will appear after the page display. It's simply the order that items are printed by the template. However, since we're editing the template, we can make the Attachment display appear wherever we want. We are going to have the Attachment display appear prior to the page display, regardless of the position selected in the view template, not for any particular reason other than to show you how to manipulate them. The way we will do this is to insert the following code just prior to the first line of the code shown previously:
This block of code checks whether we have a Page display and at least one Attachment display. If so, it creates a container around those displays. We also need to end the container following the block of code that handles the $more link:
This block of code performs the same test as the first that we inserted, and if it determines the conditions are met, it inserts the instructions to turn off floating, and then closes the container. We need to turn off floating because we will turn it on via CSS in order to have the two displays side-by-side instead of one above the other. That's it. Now we just save that file in our theme directory, in our website sites/ all/themes/acquia_slate/, and name it as we discussed above, views-view-Subs.tpl.php. With that out of the way, we can move on to the CSS changes. Our theme uses a style.css file to handle positioning and formatting. It also has a local.css file in which overrides to the styles defined in styles.css are placed. In this way, if a newer version of the theme is released, we can update the style.css file without losing the changes we put in local.css.
[ 53 ]
Attachment Views – A New Beginning
CSS Files Each theme comes with its own supporting files, including CSS files, and they are defined in the theme's .info file. The theme being used for this site, Acquia Slate, comes with the local.css file.
The following are the things that we want to accomplish with our CSS changes: 1. Have the two view displays appear side-by-side. 2. Provide some demarcation between the two using spacing and a border. 3. Format the subcontractor name to stand out from the rest of the subcontractor details. To have our two displays appear side-by-side, we will add the following entry: .view-id-Subs .view-content,.view-id-Subs .attachment{ float: left }
The first thing to note is the selectors. The content of our page display is shown in a division with the class view-content. We could have a selector of just .viewcontent, but that would affect every view-content class on every page of the website. We further qualify our selection by specifying that we only want the viewcontent class that is nested within the div with a class of view-id-Subs, which limits this selection to our Subs view. The same is true for the class attachment, which contains the content of our Attachment display. Having selected them, we specify that instead of the normal behavior for a
, where a new one begins on a new line, we want the content to float to the left, side-by-side. Having caused the two displays to appear side-by-side, we have the issue of there being no white space between them. Users need white space to imply boundaries, and to give the eyes a moment's rest while reading. Our next entry will add a right margin to the subcontractor list. .view-id-Subs .view-content { margin-right: 120px }
The next entry places a vertical border beside the Attachment display, to set the subcontractor details off from the rest of the page. .view-id-Subs .attachment { padding-left: 1em; border-left: 1px solid #dfa155 } [ 54 ]
Chapter 2
The remaining two entries are for formatting the subcontractor name. One adds a bottom margin to the
that wraps the subcontractor name, and the other increases the text size of that name, makes it bold, and displays it as uppercase. .view-id-Subs .attachment .views-field-title { margin-bottom: 6px; } .view-id-Subs .attachment .views-field-title .field-content { font-size: 120%; font-weight: bold; text-transform: uppercase; }
Having made our template and CSS changes, we need to force Drupal to evaluate the new template file. Drupal caches the theme, and would ignore the fact that we've added a template file if cache were not cleared. Whenever a template file is added or deleted, Drupal's cache needs to be cleared. Subsequent edits to the template do not require the clearing of cache. The button to clear the cache can be found at admin/ settings/performance, as shown in the following screenshot.
The fruits of our labors can be seen as follows:
[ 55 ]
Attachment Views – A New Beginning
Summary
We learned what an Attachment view is, and how it can be useful. We created a view with a Page display, and added an Attachment display to provide added functionality. We also learned a little about theming a view by creating CSS and a template file. We're off to a good start, and have several more examples of using Attachment views in different situations ahead. Let's move on to Chapter 3, Interactive Page Regions, where we'll use an Attachment view for adding isolated functionality to a "Contact Us" page, and create a small module to modify the standard Contact form.
[ 56 ]
Interactive Page Regions Drupal has a built-in Contact subsystem that can be used to send messages to site members. Our website won't be used like that, but there is a need to provide the typical contact-us mechanism where users can send a message to the site owner, but with a few extra features. In this chapter, we'll be continuing with using an Attachment view in conjunction with the page view. We're going to add a little twist, though. Sometimes, the functionality we need isn't readily available by means of a view, even with an Attachment view. That's the case in this chapter, where we'll be souping up the site's default Contact Us feature. We'll still be using an Attachment view, but simply for displaying dynamic material along with the primary view. There won't be any interaction between the Page and Attachment displays—the additional functionality will come from modifying an existing Drupal service by way of a small custom module that we'll create. We'll be using some add-on modules in this chapter—Contact blocks, Captcha, Util and Embed_gmap, as well as a custom content type, Location. You can find more information on these in the appendices. In this chapter, you will learn the following: •
How to configure Drupal's Contact system
•
What the default Contact system does (and does not do)
•
How to add just a little pizazz to a page with an Attachment view and a module
•
How to add the Contact form to a view
•
The first steps you need to take with Drupal's module architecture and hook mechanism
Interactive Page Regions
•
How to modify the Contact form via a custom module
•
How to use an add-on module to make the Contact form available in a view
•
How to create an Attachment view
Lots to do—let's get started!
Activity 3-1–Configuring the contact subsystem
1. Navigate to the Contact form admin page (admin/build/contact) and click Add category. The Contact module is installed with Drupal, but is disabled by default. This step requires that the Contact module be enabled.
2. The Contact form will open. The information that we need to provide in it is a title in the Category field, an e-mail address in the Recipients field to which the contact e-mails should be sent.
[ 58 ]
Chapter 3
3. We've made a contact form available. Normally, the form would be shown on a page of its own, but we need the form to be shown in a view, and will eventually point our menu choice to the view instead of the normal contact page. The contact form isn't a node, feed, or any of the typical constituents of a view. So, how do we bring it into one? There are different approaches, but the easiest will be to use another add-on module: Content form blocks. We'll navigate to its administration page under Settings (admin/settings/ contact_form_blocks). This step requires that the Contact form blocks module be installed. Information about this module can be found in Appendix A and at http://drupal.org/project/contact_form_blocks.
4. The Contact module allows you to create categories of contact, such as feedback to the administrator, contact between users, and so on. On this site, the only contact that will be enabled is from users to the site owner. There's not a whole lot to configure here, since we only have one category of contact configured, but this is where you select which contact category will be available as a form inside a block. The following screenshot shows this configuration form ready to be saved.
5. Having saved that information, the module will have created a block for our use in the contact-us view. Go to the list of blocks (admin/build/block) and see. Remember to scroll down to the Disabled section of the list to find the block, because it's not been assigned to a region yet. Because we named the contact category General, the block will be called Contact form: General.
[ 59 ]
Interactive Page Regions
6. We want to assign the block to appear in the content area of our page, but the theme we are working with has not exposed Content as a region for our use. Let's change that. In the directory sites/all/themes/acquia_slate is the file acquia_slate.info. Edit it. 7. There is no mandatory order within a theme's .info file, but they are small enough that you should be able to find what you need at a glance. Look for a group of lines that each begin with the word 'regions,' as shown below: regions[sidebar_first] = sidebar first regions[sidebar_last] = sidebar last regions[banner] = banner regions[header_top] = header top regions[header_first] = header first regions[header_middle] = header middle regions[header_bottom] = header bottom regions[preface_sidebar] = front preface sidebar regions[content_top] = inner content top regions[content_bottom] = content bottom regions[postscript_first] = postscript first regions[postscript_middle] = postscript middle regions[postscript_last] = postscript last regions[footer] = footer regions[node_bottom] = node bottom
8. Each of those lines defines a region to which blocks can be assigned. We need to add one. Between the regions[content_top] and regions [content_bottom] lines insert the following: regions[content] = content
9. Save the file, and then go to the Performance page (admin/settings/ performance) and click the Clear cache button. 10. Return to the blocks page and assign the Contact block to the Content region, as shown in the following screenshot, so that it will appear along with our View content.
[ 60 ]
Chapter 3
11. We need to configure the block, otherwise it will appear along with every piece of content on the site. We'll click configure, and set the block to appear only on a specific page, as shown in the following screenshot. We'll need to provide the path of that page, but it doesn't exist yet. Luckily, the block administration does not validate the path. Since we'll have to do it at some point anyway, we'll create a name for our eventual view, contact-us, and use it here.
With the contact form now being hooked into a block, and the block configured to show in a single view, we need to create that view so that we can see the contact form.
[ 61 ]
Interactive Page Regions
Activity 3-2–Creating the contact-us view 1. The contact-us view we're going to create is simply going to be the glue for our pieces. By using a content type to provide contact information on the page, the site owner can easily have different versions of the page to use at different times of the year (like Google does on their home page) simply by creating a new node of the Location content type and having the desired one enabled. The view will make use of that content. Go to the views page (admin/build/views) click Add, and choose to create a Node view.
2. At this point, we're not interested in configuring the view to provide any content. In fact, what we want to do is prevent it from showing content. The reason is that the block we created, which will contain the contact form, will appear in the content region of the page showing this view. We don't need any other content at this point. However, we cannot save this view as it is, because, by default, the Row style is set to Fields, and we have no fields selected. So, click on Row style and change it to Node. 3. Having changed the Row style to Node will allow us get past the problem of not having defined any fields, and will allow us to save the view. However, that setting without any filters in place will cause the view to select every node, whereas we want it to select none, for now. There is no filter choice for Null display, but we can accomplish the equivalent easily. Select the filter Post date and set it to a date for which we know there are no posts. 4. Lastly, we want to create a Page display and assign a path to it, so that we can access the view. Name it contact-us.
[ 62 ]
Chapter 3
5. The view is ready to save. The panel settings are shown in the following screenshot.
[ 63 ]
Interactive Page Regions
6. With our skeletal view saved, navigate to its path (contact-us) and get a first look at the current contact form, as shown in the following screenshot:
The location information isn't displayed at this time, because we have not yet created that content. The important thing here is the contact form. The site owner wants to capture when someone completes the form, which would not be available given only the form's current fields, namely Company, Street address, and Phone. There isn't an admin mechanism for adding fields to the contact form, but there is a relatively easy way to do it, once you know how, and that's by creating a module.
[ 64 ]
Chapter 3
What's a Module? A module is how we can add our own logic to what Drupal does- to add extra functionality, or to alter the behavior of Drupal's existing functionality. With some web applications, the only way to do this is to change the existing code ('core' in Drupal parlance). The problem with that is that when a new version of the application is released, not only will those changes need to be made again to the new version, but in some cases the code you originally changed will be different in the new version, so that the changes you made originally cannot be made in the same way. Fortunately, Drupal's module architecture and the ability to hook into its events remove any need to change the core code.
Let's create a module!
Activity 3-3–The Guild Builders module
Creating modules is the stuff of a book in itself. So, we're not going to approach it as a soup-to-nuts narrative. Instead, we'll go through the steps of creating our module, which will give you the basic knowledge that you need to decide whether you'd like to investigate the topic further. A module typically has up to four core files: the file core to its functionality (the .module file), a file that describes the module to Drupal (the .info file), a file that provides installation and removal instructions to Drupal (the .install file), such as for creating database tables, and sometimes included files to separate out functional parts of the module (.inc files). Our module will only require the former two. 1. Creating the .info file. Open a text editor and add a few lines. name = GBI Custom
2. This line defines the name of the module as it will be displayed in the modules listing in admin. package = Guild Builders Inc.
3. We could omit this line, which would cause the module to be located in the other section of the modules listing. However, we want it to appear in a section of its own, and this line provides a title for that section. description = Custom functions
4. The description line provides the descriptive text that appears alongside the module entry in the modules list. core = 6.x
[ 65 ]
Interactive Page Regions
5. The core entry specifies which major version of Drupal the module is meant to work with, such as 5.x, 6.x, or 7.x. version = "6.x-1.0"
6. Finally, this line specifies the version of our module. It's meant to work with Drupal 6.x and is the first version of our module, and since we will not be releasing a pre-release version (0.x), we'll make it version 1.0. 7. Our file now looks as follows: name = GBI Custom package = Guild Builders Inc. description = Custom functions core = 6.x version = "6.x-1.0"
8. We need to create a directory in which our module will live. We already have the path sites/all/modules in which add-on modules are placed. First, create the path _custom, in which to put our own modules, so that we can find them easily. Put the underscore at the start of the name so that it appears first in the directory list. 9. Next, add the path guildbuilders as the home for this module. So, we now have the path sites/all/modules/_custom/guildbuilders, save our text file to that path as guildbuilders.info.
Creating the .module file
1. Open a new blank document in a text editor. Begin this one with an opening php tag, since the module file will contain php script.
2. Next, we're going to add a function. Our connection into Drupal is provided by way of a 'hook'. Drupal and Hooks Certain events occur, in a fixed order, whenever a Drupal web page request is fulfilled. One such event is a form being created. Drupal allows us to 'hook' into this event. It provides entry into the process at the point where the form has been created, allowing the opportunity for a module (or modules) to alter the form before it is shown. This entry point is known as form_alter, and the hook as hook_form_alter. If we create a function, replacing 'hook' in the name with our own function name, our function will be executed at the appropriate time.
[ 66 ]
Chapter 3 function guildbuilders_form_contact_mail_page1_alter(&$form, $form_state) {
3. We could simply hook into the form_alter event, which would then invoke our function when any form in the website is ready to be displayed. We would then have to check to make sure that it is the form we want that is about to be rendered. Instead, we have used an alternate version of the hook, providing a function name that specifically identifies the form name in which we're interested. In the line, given previously, are the following components: 1. guildbuilders: The name of our module. 2. form_alter: The event we are hooking. 3. contact_mail_page1: The name of the form we are hooking. The hook, form_alter, is separated in this instance, because we specify which form we're altering. How do you find the form name to use? Look at the page source of the page with the form, and find the
9. We'll save the template file as views-view--prior-work.tpl.php and clear the cache. 10. Finally, we'll add some final styles to our CSS file to surround our displays with a border and some whitespace: .view-prior-work .view-content { margin: 12px 1em 0 0; border: 1px solid #4b4b4b; } .view-prior-work .attachment-after { margin: 12px 0 0 3em; float:left; }
[ 171 ]
Prior Work
That's it for this view. Let's take a look at the final version.
Summary
We created the prior-work view with three displays, two Attachments and one Page, with one Attachment being interactive, and the other not. We used a relationship with the view, and did some basic theming. In Chapter 7, we will create an interactive About Us page, with two interactive Attachment views, and a Page display that can have three different content states!
[ 172 ]
A Different 'About Us' In this chapter, we're going to spice up what is typically a functionally flat page on most sites, the 'About Us' page. The site visitor will go to this page to get information about the company, but in our case, that information can be more than the typical company history blurb. We're going to create a view with several displays, as follows: •
A link from which to select to view the company history
•
An attachment display from which to select a biography
•
An attachment display from which to select an example of prior work
•
Page displays to present the selected record from each page display
At this point, we could export the views we have already made, combine the needed elements, and import them as a new view, but it would be too complicated to show and explain here, so we'll create it. We're going to do something a little different than we have in the past couple of chapters; we'll make the small displays of selection lists the attachments, and the display of single selected records the page displays. The reason for this is that the lists from which the records are selected need to appear on multiple page displays, and attachment displays can be attached to more than one display.
A Different 'About Us'
Activity 7-1–Creating the About Us view The About us page will be a view. We'll create that before each of the displays. 1. Start by creating a new view of type Node, and name it about.us.
[ 174 ]
Chapter 7
2. Having created the view, we're looking at its panel. At this point, we haven't created a display, and we are looking at the default settings. Each display is different enough from the next that we won't use default settings. We have a number of displays to create. Let's get started.
Activity 7-2–Creating the Bio Page display
The trick behind our view is that it will have three different page displays with three different URLs. The URL selected, and thus the content of the display, will depend on whether the user chooses to see the company information, a biography or prior work. In this activity, we'll create the Page display used to show a single biography.
1. We're going to have three page displays in this view, so remove the ambiguity from this display by naming it Bio Page.
[ 175 ]
A Different 'About Us'
2. We'll be displaying only one record, so change the Items to display setting to reflect that. Click Override before updating, so that the setting change only affects this Page display.
3. The path for our page is the secret behind this view working. There will be three page displays, but only one will appear. How do we control that? Each page display will have a slightly different path. All three will contain aboutus but this one will have the path about-us/b with the 'b' for biography.
[ 176 ]
Chapter 7
4. We're going to need the URL to pass the bio node ID (nid) to the display, so that we know which record is being requested. Define an argument by clicking the + icon, and then selecting Node: Nid. Simply accept the settings in the subsequent dialog, as is, after clicking Override.
5. Select the fields to be included in this display, which are listed in the following image. The Node: Title field contains the name of the person whose bio has been selected, and the Node: Body contains the bio text.
[ 177 ]
A Different 'About Us'
6. With the Job Title field, specify that a label isn't needed.
[ 178 ]
Chapter 7
7. The photo field is a bit different. We can elect to receive the original image, but we have no idea what size that image might be. We've used the ImageCache module to define a preset, so that a 'bio image' is available to us, which will always have been scaled to a size within the parameters defined for that preset. Choose that from the format, and remove the field label.
[ 179 ]
A Different 'About Us'
8. The next field will be the Body field, which contains the text of the biography. The only change to make to it is to remove the field label.
9. The final field is the Title field, which with the Bio content type, contains the employee's name. The only change for this field is to remove its label.
[ 180 ]
Chapter 7
10. The fact is that, technically, we don't need any filters for this display, because we're providing the nid via the argument, which will determine the node we need. However, we'll create filters just to be sure, in case a manual link is entered with the wrong nid; for example, the case where someone bookmarks a display in which the node is later unpublished. Use the Node: Published and Node: Type as filters.
[ 181 ]
A Different 'About Us'
11. With the Published filter, select only published nodes.
12. The Node type filter gives the option of selecting one or more types of content. Select the Bio type.
[ 182 ]
Chapter 7
13. The final step for this display is to preview it. We'll specify the Bio Page display, and provide an argument, six, for example. The results are shown in the following screenshot.
[ 183 ]
A Different 'About Us'
Activity 7-3–Creating the prior-work display
The next display is the prior-work page display, to show the record selected from a list of completed jobs. The assembly of this display is so similar to that in Activity 7-2, that I'll forgo giving step-by-step instructions, and instead, will provide an image of the view panel with all the settings in place for this display, and identify the specifics as bullet points.
•
Make the display name Prior-Work.
•
The path should be set to about-us/p (as opposed to about-us/b for the Biography display).
[ 184 ]
Chapter 7
•
The Job photo will be used with the format set to full image, as well as the Address field.
•
The Node type filter needs to be changed to Job, and a filter added for Display completed job (Allowed values) to not be false.
Activity 7-4–Creating the About Us Page display
The display, which will present the company information, will simply display a piece of content, so the display settings will be more simplistic than the other two. Let's do it! 1. Start by creating a Page display.
2. Name this display About-Us Page.
[ 185 ]
A Different 'About Us'
3. This display will present an entire node, as opposed to the individual fields such as the other two displays. Change the Row style to Node to accomplish this.
4. Elect to display the entire node, instead of the teaser, and to not include the links that might otherwise accompany the output.
[ 186 ]
Chapter 7
5. Despite the fact that we'll be selecting the specific node to show via a filter, change the Items to display setting to 1, so that anyone subsequently looking at the view will realize that there should be only one record.
6. With the previous displays, we added a suffix to the path to differentiate them. With this Page display, simply make the path about-us, since this will be the display linked to by the menu.
[ 187 ]
A Different 'About Us'
7. We'll need two filters for this display. One filter is for Node: Published.
8. The other filter is for Node: Type.
[ 188 ]
Chapter 7
9. Our final step with this display is to preview it. Select the About-Us Page display. The results are shown in the following screenshot.
Why don't my images show in the preview? The node used above actually has an image embedded in it. What is appearing instead is the alt text for the image, in the form of name, phone, and partial address. You might notice that sometimes images appear in a view preview, and sometimes not. The reason the image doesn't appear in this one is that the image is located in the page theme's directory, and the theme being used for creating the view is not the same theme, so the file will not be found with the current theme.
How do I get rid of the post information? If your preview is showing post information (the name of the user, who posted the content, and the date it was posted) and you want to turn that off, navigate to admin/build/themes/settings. There you can enable or disable the showing of post information for each content type.
[ 189 ]
A Different 'About Us'
Activity 7-5–Creating the Bio Attachment display 1. Begin by creating an Attachment display.
2. Alter the display name, because there will be another Attachment display on the page, so a more descriptive name will help. Call this Bio Attachment.
3. We don't need this display to inherit the Page display's arguments. This display doesn't use arguments. Disable that.
[ 190 ]
Chapter 7
4. We want this Attachment display to appear no matter which Page display is being shown, so attach it to all three displays.
5. Override and remove the argument for this display. 6. For our Fields setting, select the Node: Nid and the Node: Title.
[ 191 ]
A Different 'About Us'
7. We don't want the nid to display. We simply need its value available to use in the link we will create with the node title. Exclude it from the display and remove its label.
8. The node title contains the name of the employee. The view will produce a list, and each list item will be a link to our Bio Page display. The link needs to include the nid as an argument, so that the Page display will know which node to display. Remove the label, specify that the field should be output as a link, and define that link as about-us/b/[nid], which is the path we created for the page (about-us/b) and the replacement pattern that will substitute [nid] with the actual nid.
[ 192 ]
Chapter 7
9. We may have multiple records to display, so we need a sort order. Sort based on the node title, which is the employee name in the Bio content type.
10. Sort the title in ascending order.
[ 193 ]
A Different 'About Us'
11. We need to filter the selection of nodes. The filters will be the Node: Published and Node: Type values.
12. For Node: Published, select a published node.
[ 194 ]
Chapter 7
13. For Node: Type, we want only Bio nodes to be selected.
14. The final step for this display is to preview it, and verify that the link it produces is correct. Simply place your mouse over the link to see what the browser sees.
[ 195 ]
A Different 'About Us'
Activity 7-6–Creating the prior-work Attachment display
We're going to handle the creation of the Prior-Work Attachment display in the same way as we did the Page display earlier, by showing the panel of the completed display along with a bulleted list of how it differs from the Bio Attachment display.
•
The display name is Prior-Work
•
The link created in the Node: Title field setting is about-us/p/[nid]
•
The node type filter is set to Job
•
A filter is added for Content: Display completed job (allowable values) set to Display completed job
[ 196 ]
Chapter 7
Preview this attachment and check the link.
The only thing left to do is look at the three pages as the user sees them, after some theming has been done. The three displays appear in the following images. The main page display is as follows:
[ 197 ]
A Different 'About Us'
The Prior-Work display is as follows:
The Bio display is shown as follows:
[ 198 ]
Chapter 7
Summary
In this chapter we created the 'Abous-Us' view with five displays, three Page displays, and two Attachment displays. In Chapter 8, we will create a control panel-like view for the management, so that you can have access to all the various content from one place!
[ 199 ]
Control Panel We've used a number of custom content types throughout this book (see Appendix B for more detail). The various backend users and roles, are free to go to the administrative page for content and investigate nodes of interest, or to create a view to present them as teasers. However, that isn't a very effective or user-friendly way. In this chapter, we're going to create a control panel, with one main view portal, and small displays from which to select the content to view. We're going to create a view with several displays, as follows: •
An attachment display for each content type
•
A portal for viewing the select node
•
The attachment displays themed as drop-down selections
Control Panel
Activity 8-1–Creating the Control Panel view Begin by adding a new view of the node type.
1. Make some settings to our default display that will be common among the Attachment displays. That way we don't have to set them separately for each display. Start by changing the displayed items from 10 to 0 to remove any limit. That might result in far too many for a normal display, but we'll be using drop-down list boxes.
[ 202 ]
Chapter 8
2. The fields we will need in each case will be the Node ID (Nid) for creating a link, and the Title, for the link text. Both are in the Node: section.
[ 203 ]
Control Panel
3. Remove the label of the Nid field.
4. The Node title will be the field that we use in the drop-down lists. Remove its label.
[ 204 ]
Chapter 8
5. It's a safe assumption that since the Node title is the only field that will be visible, it will also be the field on which we sort.
6. Sort in ascending order.
[ 205 ]
Control Panel
Normally we would create a filter to select only published nodes, but this display isn't meant for the viewing public, it's for the site owners, and they will want to see every node, not just the ones that are published.
Activity 8-2–Creating the Page display
1. We will configure the Page display after we're done with the Attachment displays, but we should create it now so that we have something to which we can attach the Attachment displays.
2. We also need to create a path for the display at this point. The View validation logic doesn't like having a Page display that isn't assigned to a path, and will complain about it. We'll want to preview our Attachment displays, and the preview won't run if validation fails. So, name a path.
Activity 8-3–Creating the Attachment displays
We'll be creating an Attachment display for each of the content types in use on the site. Each display will be precisely the same as the next, other than the Node type and Display name. We'll create the first one step-by-step, and then simply note the additional displays that are created in the same way.
[ 206 ]
Chapter 8
1. The first step will be the creation of the display.
2. We'll name this first one Bio Attachment.
3. Change the Inherit arguments setting, since the display will list all the nodes of the Bio content type, we don't need arguments.
4. Next, specify that the Attachment display should be attached to the Page display.
[ 207 ]
Control Panel
5. We made most of our selections on the Default page, so all that is left to do is to create a filter to specify the node type. Make sure to click Override before selecting the node type. Return to the Page display after creating this Attachment display, and remove any fields listed under Fields that should not be there.
[ 208 ]
Chapter 8
6. This display should select only Bio nodes.
7. Let's preview our display. We'll select Bio Attachment for the Live Preview display type.
[ 209 ]
Control Panel
Activity 8-4–Creating the other Attachment displays
We're going to repeat the steps in Activity 8-3 for each of our content types: AboutUs Info, Job, Location and Subcontractor, naming them appropriately and selecting the matching node type for the filter. The previews for each are as follows:
[ 210 ]
Chapter 8
Activity 8-5–Configuring the Page display
We already have created the Page display and assigned a path to it. Now, we'll finish configuring it. There are two different approaches we could use in this display regarding the content. We could make the display aware of the type of content it is displaying, and then theme accordingly for each content type. That's a lot of work, so we won't do that unless the need arises. Instead, we'll have the Page display present all content in the same fashion, without knowing which node type is being displayed. How? We're going to pass the Nid as an argument. If we elect to display the Node instead of Fields, with the Nid to define which node, we have all that we need. 1. Change the Row style to Node.
2. Elect to show the complete node, and to not include links.
[ 211 ]
Control Panel
3. This view is going to be for the Guild Builders staff only, so change the Access to being Role-based.
4. Select the management role.
[ 212 ]
Chapter 8
5. Create a menu item for this View. We already have a Guild Builders menu, for the use of the staff. Add it to that.
6. Create an argument for the display, which is important unless we want it to select every node. The argument will be the Nid.
[ 213 ]
Control Panel
7. If the page is requested without an argument, force the Nid for the About Us node. There is a chance, however, that at some point that node might be deleted, and thus that Nid will not longer exist. In that event, display the empty text.
8. Create some empty text.
[ 214 ]
Chapter 8
9. We're ready to preview. First, preview with no argument. In the following image, you'll see that the About Us node is selected, as we defined earlier.
10. Preview using an argument.
[ 215 ]
Control Panel
Activity 8-6–Theming the Attachment displays
1. We don't need to theme the Page display, because it will be displaying entire nodes. What we want to theme are the Attachment displays; to have each of them display a select box containing the node title links. To do this, theme each row of output as an option for a select control, and then embed the rows in that control. This is done in two different template files, since one has visibility to each row as a group of fields, and another to all the rows as a collection. 2. We have no need, at this point, to discern which attachment we're working with, because each will be handled in the same way. So, copy the unformatted template file from /sites/all/modules/views/theme. This is the file that contains all the rows as one collection. Name it the most specific theme name listed—under Information for an attachment in our view—that does not specifically number the attachment, which is: views-view-unformatted--control-panel--attachment.tpl.php. 3. Following are the initial contents of that file:
$row): ?>
It's not easy on the eyes, with the php tags encasing each line. This style has not been without opinions on both sides, but the prevailing opinion is that it's easier to debug and faster to drop in HTML between the lines than it is to have the HTML encased in strings instead of the PHP being encased in tags.
4. Notice the highlighted row towards the middle of the listing; a for each statement. It loops through each row of our selected content type and prints it. Therefore, this file is being called once for each of our Attachment displays.
[ 216 ]
Chapter 8
5. We're going to modify it to format each row as a select control with options. Change the lines from the highlighted line to the end to read as follows:
6. What we've done is eliminate the
tags encasing each row; because each row will be a select option, so should not be a
. We've also embedded the loop within