Drupal 7 Webform Cookbook
Over 70 recipes for exploiting one of Drupal's more popular contributed modules
Vernon Denny
BIRMINGHAM - MUMBAI
Drupal 7 Webform Cookbook Copyright © 2012 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: May 2012
Production Reference: 1090512
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84951-648-8 www.packtpub.com
Cover Image by Asher Wishkerman (
[email protected])
Credits Author Vernon Denny
Technical Editors Manasi Poonthottam Ankita Shashi
Reviewers Richard Carter Richard Eriksson
Project Coordinator Sai Gamare
John K. Murphy Jeff Smith Ravishankar Somasundaram Acquisition Editor Usha Iyer Lead Technical Editor Dayan Hyames
Proofreader Bernadette Watkins Indexer Hemangini Bari Production Coordinator Alwin Roy Cover Work Alwin Roy
About the Author Vernon Denny was born and bred in a small city called Klerksdorp in the north-west of South Africa. Vernon now lives in Johannesburg with his wife, daughter, and supercilious cat. Despite standing two meters tall in his thinnest socks he has a nervous apprehension of heights. After explaining the vagaries of the insurance industry to an IBM iSeries computer in RPG and PHP during the typical working day, he loves to help out on the Webform issue queue on the Drupal website. In between all of this, he also keeps himself busy learning about the GNU/ Linux operating system and the freedoms arising from the Free and Open Source Software movement. When a computer keyboard is out of reach, Vernon is either playing games with his daughter, hiking with the family, or irritating them with his attempts to learn the guitar. A massive thank you to Nathan Haug (also known as quicksketch) for making the Webform module what it is today. I do not know how you make the time, but like many others around the world, I am very, very grateful. Dries Buytaert and the entire active Drupal community of coders, testers, maintainers, and users are lauded for their commitment to putting Drupal out there and maintaining its position as a high-quality, stable, and leadingedge web content management system. Words cannot possibly express the depth of my gratitude to Sai Gamare, Dayan Hyames and Usha Iyer of Packt Publishing for their patient insistence that deadlines should be met. It was rough going for a while, but you guys really helped me see it through in the end!
About the Reviewers Richard Carter is the Director at Richard Carter Consultancy Ltd (http://www.
richardcarterconsultancy.com), an open source web software consultancy, and Creative Director at Peacock Carter Ltd (http://www.peacockcarter.co.uk), a web design and development agency, both based in the North East of England. He has helped clients around the world get to grips with open source software, including Directgov, NHS Choices, Business Link, University College Dublin, and the German Historical Institute London.
Richard is the author of MediaWiki Skins Design, Magento 1.3 Themes Design, Joomla! 1.5 Templates Cookbook, and Magento 1.4 Themes Design. He has acted as a technical reviewer on MediaWiki 1.1 Beginner's Guide, Inkscape 0.48 Essentials for Web Designers, Definitive Guide to Drupal 7, and Drupal 7 Business Solutions, and is a co-founder of the Drupal North East user group (http://www.drupalnortheast.org.uk). He blogs at http://www.earlgreyandbattenburg.co.uk and tweets nonsense at http://twitter.com/RichardCarter. I would like to thank the author of the book and the wider Drupal community for dedicating time to help others learn Drupal, which has changed, for the better, beyond almost all recognition in the last few years.
Richard Eriksson has been a member of the Drupal community since 2004 (visit his
profile at http://drupal.org/user/8791). Richard has worked on the community support and systems administration team at Bryght, the first commercial Drupal venture (later purchased by Raincity Studios), and later OpenRoad Communications, where he helped build video-intensive multilingual Drupal websites promoting video games. He also maintains an independent consultancy called Ethical Detergent specializing in Drupal maintenance and support. On Drupal.org, he maintains the Pirate and RSS Permissions modules, the Cherry Blossom Theme, and most recently, the Readability Button module. He writes occasionally on his blog, Just a Gwai Lo (http://justagwailo.com/). He has also worked on the following books:
Drupal 6 Theming Cookbook Drupal 7 Theming Cookbook
John K Murphy is a software industry veteran with more than 25 years' experience as
a programmer and database administrator. A graduate of the University of West Virginia he began writing computer games in the 1980s before pursuing a career as a computer consultant. Over the years, John has enjoyed developing software in most major programming languages while striving to keep current with new technologies. In his spare time, John enjoys scuba diving, skydiving, and piloting small planes. He lives with his wife and two children in Pittsburgh, Pennsylvania.
Jeff Smith grew up in Odon, Indiana before moving to Indianapolis. He has 15 plus years of experience in the IT Industry as well as 9 months experience as a .NET developer. He loves learning new technologies and dabbles quite a bit on the side. He works for the Indiana Department of Workforce Development as an Application Developer. He has reviewed the books CakePHP 1.3 Application Cookbook and Drupal 7 Business Solutions. I would like to thank my girlfriend Dawn for understanding why I try to learn new technologies and review books. I would like to thank Packt for giving me an opportunity to help out on this book, the other two titles I have worked on, and I look forward to helping out on any books I can in the future.
Ravishankar Somasundaram has over six years of experience in providing solutions
to clients across multiple sectors and domains. Being more passionate about learning and teaching, he also strongly believes that the sole purpose of learning is to make our minds think in different perspectives and facilitates the same in his training sessions through a blended learning approach mainly focused on how to learn to learn. In his lower schoolings, apart from winning several prizes in science projects, he was awarded the title Junior Scientist in an inter-school science fest for a model display on Evolution of Airplanes through Aerodynamics by the committee consisting of people from ISRO. This was one of his major childhood achievements. His final year college project was aimed at eliminating the scenario of English alone being the medium of programming in all programming languages, which restricts people who don't know English getting into the field of IT and implementing their ideas. The project was selected and funded by MIT NRCFOSS and considered as a landmark. Being one of only seven people from India and the only one from Tamilnadu as an official third-party developer of Moodle code, Ravi shares his knowledge by helping people on the Moodle official forum and on IRC. He has also presented a paper in the ninth International Tamil Internet Conference on Moodle: For Enhanced Learning which talks about leveraging Moodle's capability to expand the user base for one of the oldest languages known to mankind—Tamil. Ravi was a Freelance IT Consultant delivering solutions to firms irrespective of technical, non-technical, or business domains. Currently he works for Thirdware Technologies as a Technical Analyst and Chief Architect heading the R&D Division. Recently he represented his company at an international conference Yugma—Unleashing the Innovation Potential with an idea which uses artificial intelligence to empower the next generation of enterprise mobile solutions. I am thankful to all the people I have met, for they have contributed to the cause of my growth either by being an inspiration or personally guiding and pointing me in the right direction when facing challenging situations, or continuously throwing critiques, making me recognize there is always an area for improvement in my career and personal life. Last but the foremost, I dedicate all my accomplishments to my parents, sister, and other relations for all the faith, hope, love, and support they have given me.
www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe? ff
Fully searchable across every book published by Packt
ff
Copy and paste, print and bookmark content
ff
On demand and accessible via web browser
Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
To my loving wife and inspiring daughter—every day can be a big day
Table of Contents Preface 1 Chapter 1: Setting up Webform 5 Introduction 5 Downloading and installing Webform 6 Configuring Webform for our website 8 Setting user roles and permissions 12
Chapter 2: Trying Out Webform
15
Chapter 3: Working with Submissions
37
Introduction 15 Creating a Webform node 17 Adding textfield components to our Webform 19 Cloning components 24 Adding e-mail components 25 Adding textarea components 26 Adding fieldset components 27 Adding select components 31 Configuring a reply e-mail 33 Testing our Webform 34 Introduction 37 Viewing submissions metadata 38 Viewing submissions 41 Editing submissions 44 Analyzing submitted data 47 Downloading submissions 48 Deleting submissions 52 Clearing the database 53 Changing Webform results defaults 54
Table of Contents
Chapter 4: Discovering More Components
59
Chapter 5: Tweaking the Form Settings
77
Chapter 6: Extending Webform
97
Introduction Adding a page break component Adding a markup component Adding a hidden component Adding a grid component Adding a date component Adding a time component Adding a file component Enhancing component descriptions with HTML
59 60 62 65 67 70 72 73 75
Introduction 77 Confirming submissions 78 Limiting submissions 82 Closing and reopening forms 84 Limiting access to forms 85 Displaying Webform as block 87 Saving draft submissions 91 Warning about previous submissions 93 Customizing submit button text 94 Introduction Enabling the Select (or other) module Using the Options Element Defining custom option lists Enabling date pop-up Sending HTML e-mails Preventing spam with CAPTCHA Advanced data validation
97 98 100 102 105 107 111 114
Chapter 7: Theming Webform
119
Chapter 8: Acting on Webform Submissions
137
Introduction Preparing our custom theme Adding custom CSS Adding JavaScript tricks Theming the confirmation page Theming Webform e-mail headers
119 120 123 127 131 134
Introduction 137 Modifying submitted data 138 Adding custom validation 146 ii
Table of Contents
Chapter 9: Creating Webform Components
159
Chapter 10: Creating Submission Actions
189
Chapter 11: Presenting and Managing Data
209
Chapter 12: Going Out of the Box
229
Index
249
Introduction Creating the component module Defining component features Defining component defaults Editing components Rendering components Displaying and reporting component data Analyzing component data Validating submitted data Testing the module Introduction Creating a new select component Creating the module Creating a conditional action Adding a menu item Confirming the requested action Updating a submission Sending an e-mail Testing the module
Introduction Building custom reports Counting Webform submissions with views Tracking changes to submissions Introduction Building a survey form Defining same-page conditional fields Validating on the client side Importing submissions
159 162 163 167 168 171 173 176 178 181
189 191 194 195 197 199 200 202 205
209 210 216 226 229 230 234 239 242
iii
Preface Consistently ranked in the top 15 of the most installed Drupal contributed modules (see http://www.drupal.org/project/usage), Webform has proven to be a must-have extension on Drupal websites the world over. There is simply no better way to rapidly create forms on our Drupal websites. After taking an in-depth look at working with Webform components and submitted data, we delve into enhancing our forms with some programming exercises that introduce the Webform API. Of course, no Drupal module is an island, so we cover several of the contributed modules that extend Webform to add value to our forms and the way they are experienced.
What this book covers Chapter 1, Setting up Webform, explains how to install the Webform module and covers a brief discussion of the Webform configuration options. Chapter 2, Trying Out Webform, introduces Webform components, building, and testing our first Webform module. Chapter 3, Working with Submissions, covers the Webform backend and explains how to work with data submitted to our form. Chapter 4, Discovering More Components, continues the exploration of available Webform components. Chapter 5, Tweaking the Form Settings, covers how to customize our form’s user interface and feedback to respondents. Chapter 6, Extending Webform, discovers additional modules to enhance the user experience of our form, protecting our forms with CAPTCHA, and an introduction to the Webform API. Chapter 7, Theming Webform, explains how to make use of the Drupal theming layer to give our form a look and feel all of its own.
Preface Chapter 8, Acting on Webform Submissions, creates custom modules that interact with user submitted data, adding custom validation rules. Chapter 9, Creating Webform Components, explains how to build our own custom Webform component from the ground up. Chapter 10, Creating Submission Actions, discusses carrying out multiple actions with a single click. Chapter 11, Presenting and Managing Data, explains how to make use of extra modules to produce customized submitted data listings and covers how to keep track of changes made to submitted data. Chapter 12, Going Out of the Box, discusses displaying and hiding fields based on previous input, validating input data on the client side, and importing submissions.
What you need for this book To follow along with the exercises and discussions in this book, you will need a working Drupal 7 installation and access to the Internet. Your Drupal installation may be remote (that is, hosted on a web server) or, preferably, a local installation on your PC or laptop. Some experience with the PHP programming language is recommended before tackling the programming exercises, but this is not an outright requirement as the code samples have been thoroughly tested. The programming tasks covered within this book can be coded with any standard plain text editor, although a programming editor is advised.
Who this book is for Written as a guide for Internet users and developers alike, Drupal 7 Webform Cookbook gives you the tools needed to turn your Drupal website into an information-gathering superhighway. Basic knowledge of Drupal is required.
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: “ This is to ensure that the %useremail token substitution works as expected.” A block of code is set as follows: name = Webform Custom description = Customize Webform Results page. core = 7.x 2
Preface package = Webform dependencies[] = webform
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: name = Webform Custom description = Customize Webform Results page. core = 7.x package = Webform dependencies[] = webform
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: “The Submit button is universally understood as it appears on a majority of forms on the Internet.”
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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
[email protected]. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, 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.
3
Preface
Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
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 errata submission form 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.
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.
4
1
Setting up Webform In this chapter, we will cover the following: ff
Downloading and installing Webform
ff
Configuring Webform for our website
ff
Setting user roles and permissions
Introduction In this chapter, we are going to extend our Drupal installation by adding the powerful Webform module. Drupal is a very capable Content Management System (CMS) as it stands. However, it cannot inherently do everything you may want it to do. A rather clever solution to this problem is the Drupal module application programmer interface (API), enabling developers to create chunks of functionality as Drupal plugins that website administrators can use to customize their sites. The Webform module facilitates two distinct, yet related, sets of functionality. First, it is a great tool for creating forms designed to capture required data from users, such as a customized Contact Us form for example. Secondly, Webform has a backend interface for website administrators to work with the submitted data. We can see then that Webform is designed for scenarios where many people (for example, users, subscribers, and so on) are submitting data handled by a small group of administrative users. Submitted Webform data is not considered to be content. This is diametrically opposed to modules such as the Content Construction Kit (CCK) or the Fields modules, where the purpose is to help us build pages that accept data to be used as website content, that is, many people submit data for viewing by many people.
Setting up Webform Apart from supporting all the standard HTML form input elements, such as textfields, radio buttons, and selection lists, Webform also offers some custom components, such as survey grids and date or time fields. All supported components include data validation options and various display options. For example, Webform has an e-mail address component which will automatically validate that submitted e-mail addresses are correctly formed, that is, they look like real e-mail addresses. We may specify mandatory fields (that is, the form user may not leave them blank), or even that only unique values may be submitted (that is, ensure that no other submission carries the same value in a specific field). Additional to the form itself, Webform also enables us to set up a variety of automatic response e-mails to submissions. Whenever a submission is made on the form, we may configure Webform to send an e-mail to the submitting user confirming receipt of their submission, as well as sending a notification e-mail to an administrator to advise them that a submission has occurred on the form. Administrators have access to view and edit submitted data, and resend e-mails, as well as the ability to download submitted data into spreadsheets. Webform even includes some basic statistical analysis of submitted data. True to the spirit of Drupal, Webform is itself extendible via its own API. Several contributed modules exist that enable us to make our specific Webform installation bigger and better. When we cannot find a module that offers the functionality we seek, we may extend Webform by developing our own custom modules. We will better understand the benefits that Webform offers us by getting stuck in and utilizing it. Before that can happen, we need to install Webform and get it properly set up to work on our website. After Webform has been properly installed, we'll take a look at some global configuration options before getting started with our first form.
Downloading and installing Webform We are now going to install and enable the Webform module in our Drupal site.
Getting ready To experience the richness of Webform an existing Drupal installation is required. This could be a local installation (that is, on your own PC or laptop) or a remote installation on a web server. Visit the web page http://drupal.org/start to obtain the latest version of Drupal. A detailed installation guide for Drupal can be found at the http://drupal.org/ documentation/install web address (see, in particular, the section on Local Server Setup if you plan to test Drupal and Webform on your local computer).
6
Chapter 1
This book is written for Drupal 7 and that would be the recommended version for you to install. The Webform module itself is maintained for both Drupal 6 and Drupal 7 in terms of functionality, but you will find that the location of some tabs, links, and buttons vary between the two versions. Screenshot images in the pages and chapters that follow will reflect the Drupal 7 interfaces only.
How to do it... 1. Let's download the latest Webform version from the projects home page at http:// drupal.org/project/webform. Typical to most project home pages, the Webform page starts off with a brief overview of what kind of solutions the module presents and a screenshot of a sample Webform. You're welcome to read through all the information presented, perhaps even follow one or two of the links, but the bit we're interested in right now is the Downloads heading towards the bottom of the page.
2. Click on the .zip (Microsoft Windows, Linux, Mac OS) or .tar.gz (Linux, Mac OS) next to the version with 7 as its first digit (we're working on Drupal version 7). 3. Save the compressed file to the /sites/all/modules directory in our Drupal installation. 4. Once it has downloaded, we extract the compressed contents using whatever tool is available for our system (normally found by right-clicking on the compressed folder). 5. A Webform folder will now be created within the /sites/all/modules folder of our Drupal installation. 6. The curious may now enter the Webform directory, read the README.txt file and perhaps browse around the Webform system files and folders. We must be careful to not inadvertently change the contents of any of the files though! 7. Enabling plugin modules is an administrative action so we are going to need to log in to our site as administrator (the user we created when we installed Drupal) to continue the installation. Let's fire up our favorite web browser, navigate to our home page, and log in.
7
Setting up Webform 8. In the administrator menu bar, we need to click on Modules:
9. Scroll down to the very bottom of the Modules page until we get to Webform. 10. Click on the checkbox next to the Module name to select it:
11. Finally, click on the Save configuration button. The page can take several seconds to re-load, but do not panic! The Webform module is busy creating database tables and identifying itself to the Drupal core system.
How it works... An aspect of Drupal that makes it such a powerful tool for constructing websites is the fact that it is extensible. The underlying core system has been put together in a way that permits developers to add plugin functionality without needing to change the core Drupal program files. It really is just a case of plug it in and switch it on!
Configuring Webform for our website Now that we have Webform installed and enabled, let's take a look at some of the global configuration settings that will apply as defaults on every piece of Webform content that you create on this site. Webform provides a highly flexible and configurable content type. Certain options have been identified as being generally constant for all Webforms on a particular site and these have been isolated on the Webform settings page.
8
Chapter 1
How to do it... The global Configuration settings for Webform can be reached either by clicking the Configure link next to Webform on the Modules page, or by clicking on Webform settings under Content Authoring on the Configuration page (click Configuration in your administrative menu bar).
How it works... The options and settings we select here will apply as default values on every new Webform piece of content we create. Many of these may be overridden in the configuration settings of specific forms if required.
There's more... Understanding the configuration options will give us a good overview of Webform in broad strokes. As we progress through the book with the demonstration Webform we will discover the finer nuances in greater detail. We will not be changing any of these default settings at this point, but we will briefly discuss what they mean in order to get an idea of the scope of Webform. As what follows is intended as an introductory overview, the next few paragraphs will be easier to follow while referencing the Webform settings page.
Webform-enabled content types To promote flexibility, the components of Webform may be associated with various types of content. A basic Drupal installation comes with two basic content types, Basic Page and Article. With this setting we can extend the existing content type by making Webform available within it. This permits us even to create a custom Drupal content type while leveraging the power of Webform.
Webform components The purpose of Webform is to facilitate the creation of information-gathering web pages and to provide meaningful back-end support for administrators who need to work with that data. Over the years, Webform has developed a set of components which blend with ease of use for the end user, as well as provides both convenience and control for website administrators. The components are so named because they are, in reality, more than just data fields. A component encapsulates the visual aspects of the field as it will be shown on the form and other output media, default validations to apply to the specific field type, specialized handling and formatting of submitted data for inclusion in spreadsheets for download, and so on.
9
Setting up Webform Each component type represents a different kind of data. The validation of a date, for example, is naturally quite different from rules that would apply to an e-mail address. While many characteristics and settings are common to all components (such as field label for example), each component has their own specific settings and requirements for further handling. Aside from unique validation requirements, some components also have specialized methods of rendering (that is, how they will look, or be drawn) on a web page. The date and time components, for example, are automatically rendered as appropriate drop-down lists, whereas the file component comes with a browse button.
Any components that are unchecked on this page will not be available to you when you start building forms.
Default e-mail values Each Webform can be configured to send one (or more) e-mails when a submission is received. It is customary to send a confirmation of a submission to the end user via e-mail, but you can also have Webform additionally send e-mails to one or more administrators. Specifying default values for the automatically generated e-mails here will save you the labor of typing these out on each and every Webform you create on the site:
10
Chapter 1
Advanced options There are forms you want to be filled out by any visitor to the page and other forms you would prefer to have only filled out by users registered on your site. Some forms may be filled out multiple times by the same person, others may only be filled out once. Webform provides some methods of handling access to forms and controlling the number of submissions from a particular source:
A frequent complaint on the Webform issue queue (http://drupal.org/project/ issues/webform) is that "Webform is not sending out e-mails!" Quite often, the challenge lies with the operating system of the hosting server. Some Microsoft-based (IIS) servers cannot handle long-format e-mail address headers. If your site is hosted on such a server and you experience difficulties with e-mail, you will need to come to this page and try specifying a different e-mail address format. See http://phptutorial.info/?mail under the Notes heading for a description of the problem. Part of the awesome functionality that Webform makes available is the facility to download all (or just some of) the data submitted on a form in pseudo-spreadsheet format, such as CSV (Comma Separated Values) or tab separated values files. You may set defaults here that will save yourself and other administrators the bother of specifying them on every occasion that data needs to be downloaded.
11
Setting up Webform
Setting user roles and permissions Not only does Webform enable us to control who may submit data, it also provides a range of permissions regarding who may create or edit Webforms, who may access submitted data, and even who may change submitted data.
Getting ready In the website administrator menu bar, click on People and then on the PERMISSIONS tab at the top-right of the screen, shown as follows:
Permissions are all about "who may do this action" or "who may access this content". It goes around what various users are permitted to do or not permitted to do. Carefully read the paragraph at the top of the page regarding permissions, giving special attention to the closing sentence. Take this information to heart and let it guide your decision-making when assigning roles and responsibilities:
How to do it... Scrolling down to the bottom of the page we find a heading for Webform with several permissions listed. By default, no authenticated (that is, logged in) user may create or change Webforms, nor access submitted data, not even their own.
12
Chapter 1
Reading the text under the various permission labels, we notice that anonymous users are completely banned from most activities. For the purposes of later experimentation, let's permit authenticated users to access and alter their own submissions after the fact by granting them authority to Access own Webform submissions and Edit own webform submissions by checking the corresponding boxes in the Authenticated User column and then clicking on the Save Permissions button, as shown in the following screenshot:
Scrolling halfway back up the page so we are able to view the list of permissions under the Node heading, we find several more Webform permissions. The permissions listed here are focused on Webform as a Drupal content type, in contrast to the permissions we looked at previously which concerned themselves more with Webform data.
13
Setting up Webform Looking at the options here, we can readily see that it is possible to create a user role that can create and delete its own Webforms, but cannot edit or delete Webforms created by a different role. With careful planning we can create very hierarchical structures in terms of user roles and their corresponding permissions.
How it works... Programmed into Webform (and all other facets of Drupal) are several checks to determine whether a user is authorized to carry out a requested action or view requested content. If the user or role permissions are not set, the requested action is ignored and an error message output is displayed on the screen. By checking the boxes for authenticated users as we did previously, we are allowing authenticated users to return to forms that they previously submitted and make alterations to the submitted data. They will not, however, be able to delete their submission because the Delete own webform submissions permission is not checked. We must be very careful when assigning permissions. If we were to accidentally check the box Access all webform results for authenticated users, then every registered user of our site would be entitled to download the data entered by every person who has submitted information on any and every Webform across our site. That is probably not a very good idea!
There's more... Drupal is, in general, a security conscious environment. Users of the site are, on first principle, denied authority on most activities and resources until fully authorized to them by the website administrator. The philosophy of 'Safety First' applies also to contributed modules such as Webform. Why is this important? Well, just as we expect other websites to safeguard our personal information, so will our end users expect us to treat their submitted information with utmost circumspection. There is a large measure of implied trust on the part of anyone who submits information to a website. That trust may not be violated if we expect to retain our integrity and reputation. Management of user roles and permissions can become quite a complicated task, depending on the size and scope of your web application. For more information on creating and managing user accounts and user roles, visit the following documentation web pages of drupal.org: Roles: http://drupal.org/getting-started/6/admin/user/roles Accounts and roles: http://drupal.org/node/22284
14
2
Trying Out Webform In this chapter, we will cover: ff
Creating a Webform node
ff
Adding textfield components to our Webform
ff
Cloning components
ff
Adding e-mail components
ff
Adding textarea components
ff
Adding fieldset components
ff
Adding select components
ff
Configuring a reply e-mail
ff
Testing our Webform
Introduction A tool that offers such a broad spectrum of functionality can appear very complex. While there are several layers to the functionality that Webform presents to us, it becomes quite a simple tool to use after just a little bit of practice. In this chapter, we are very rapidly going to create a form which will handle the registration of speakers who will deliver presentations at our fictitious conference. In later chapters this first form will be extended to demonstrate additional features of the Webform module.
Trying Out Webform It is just as well to take a moment now to consider the preparatory work that goes into a well structured form, particularly when there are many input fields required. Clearly one would not lose too much sleep over a form that needs only five fields, as there is not much that can go wrong in terms of layout and cohesiveness. However, when we get to something a little more bulky, with over fifty required inputs for example, then we should plan our way forward with some care. Perhaps the two most important criteria to consider in general form structure are sequence and grouping. It would be surprising to us if a conference registration form were to first ask whether we would like breakfast included in our hotel rates before asking whether we actually require accommodation at all. Similarly, we would be somewhat taken aback if we needed to fill in our first name on page one and our surname on page four! In the general case, it makes sense to start the form design process at as high a level as possible. Of course, it also helps to have knowledge of all of the business rules to do with speaker registrations while we're busy. All too often a carefully planned form has to be almost completely reorganized and reworked because the designer lacked some critical item of information or misunderstood the purpose of an element of data. In our scenario, where we're designing a form for the registration of speakers, we need to find out from the conference organizers exactly what information they require to ensure that the speakers have an enjoyable conference experience. It is necessary, also, to ensure that information deemed to be required is, in fact, pertinent to the situation. For example, while it is true that speakers are people and most people have feet, the speaker's shoe size is not an important piece of information to have unless the organizers are handing out shoes to the speakers. Every aspect of our form needs to be evaluated from two entirely different points of view: that of the end user who will fill out the form and that of the administrative users who will make use of the data gathered by the form. There should be no information requested of registering speakers that is not required by the organizers to aid in their planning and execution of a successful conference. Any information that we do request should be laid out in a clear and logical fashion to avoid any frustration or confusion on the part of persons registering via our form. The high-level design of the speaker registration form we are about to put together is as follows: ff
Speaker information
ff
Presentation information
ff
Additional activities
ff
Accommodation requirements
16
Chapter 2
Creating a Webform node Let's forge ahead now and create a piece of Webform content to define our speaker registration form.
Getting ready We need to be logged into our site as an administrator with Webform: Create new content permissions to continue. For the purposes of this demonstration it is best if you are logged in as the main site administrator to avoid difficulties with permission issues, as we were when we installed and enabled Webform.
How to do it... 1. Click on Content in the administrative menu bar at the top of the screen, then click on the Add content link. 2. The various types of content available on your site are now listed on the page. We want to select the Webform content type. 3. Let's give our form a meaningful name and enter the text Speaker Registration in the Title textbox. 4. The Body text area immediately below Title gives us the opportunity to provide an explanatory note about the purpose of the form, so let's enter the following text: Speakers at the Fictitious Conference are requested to fill out the form below to ensure an enjoyable conference experience.
17
Trying Out Webform 5. Check the box next to Menu settings, so that our form is accessible from standard site navigation. The default settings that appear are fine as they are. 6. Now let's click on Comment settings and select the Closed radio button to disable comments for our form. 7. When we click on the Save button we will be redirected to our new Webform's edit page and we're ready to build our form in earnest.
How it works... Having created a Webform node (content type), we now have a standard Drupal container for our Webform content. All of the activities that follow in this demonstration will be applied within this node. Drupal automatically assigns a number, called a node ID, to each new piece of content. This number is used within the underlying database to link various database tables and their rows of data. When we installed and enabled the Webform module in Chapter 1, Setting up Webform, the installation process created several new tables in our database to store information about Webforms. These tables provide storage areas for information regarding different aspects of each Webform we create on our site. The information we entered previously has been written to the Drupal system node table and to the main Webform table. As we progress through the various phases of building our form, adding form components, configuring response e-mails, and making test submissions, we will be populating additional Webform system tables in the database. The node ID helps the system identify which specific Webform node each bit of data belongs to.
There's more... If at a later point in time we decide that we would like to enable site visitor comments for our Webform or change the menu settings, we can return to the node settings page by clicking on the EDIT tab. To view what our form currently looks like we may click on the VIEW tab, as shown in the following screenshot:
18
Chapter 2
Adding textfield components to our Webform The purpose of Webform is to enable rapid form development, so we're going to add our first component and specify some settings for it. To avoid repetition in the process descriptions when adding other components, we will go over the settings of this first component in great detail. As we move on to additional components, the process descriptions will only deal with new settings specific to that component type. Due to the practical nature of this demonstration, it is recommended that we read the following while referring to the relevant on-screen displays.
19
Trying Out Webform
Getting ready When we saved our node we were automatically redirected to the page that enables the adding of components. Any time in the future we need to add or make changes to any of our form components, we can click on the WEBFORM tab above our form and then on the Form components subtab as shown in the following screenshot:
How to do it... 1. The first field on the form is going to be where we can capture the first name of the registering speaker, so let's enter the text First name in the textbox that reads New component name under the heading of LABEL. 2. The type of component we wish to add is a textfield, so ensure that textfield is the selected TYPE in the drop-down list. 3. We will want to force registering speakers to enter something in this field as their names need to be known, so let's check the box under MANDATORY and then click on Add to create the component. 4. Every component has additional settings, which we can use to manipulate the display of the component, or affect the validation of user entered data. The component settings page we have been redirected to exposes these additional settings. Because each component type is different, there will be differences in the settings that will be shown on this page for each component type. For now though, we will accept the defaults and click on the Save component button at the bottom of the page to return to the Form components overview page:
20
Chapter 2
Our First name textfield has been saved and is shown in the components table. The hyphen in the VALUE column indicates that we have not specified a default value for this component on the component settings page.
How it works... When the form is rendered, that is, shown to site visitors, the component name we just supplied will be shown as the field label. A red asterisk will appear after the label to indicate that the field is a required input – if the site visitor leaves it blank, Webform validation will not allow the form to be submitted.
There's more... After clicking on Add on the Form components page we are redirected to the component settings page where we can fine tune how the component will be displayed as well as additional validation rules.
Label This is the field name we entered on the previous page and can be changed at any time. When the Webform is rendered this is the label that names the input field. It is a required field on the settings page and will also be used to identify the column of data in reporting.
21
Trying Out Webform
Field key The field key is automatically generated by Webform and is based upon the very first name given to a component. This key is used to identify the component internally to the system and is built using rules specific to database and programming languages. As indicated by the red asterisk, this is a required field on the settings page. Should the component label above be changed at any time, the field key will remain the same as it was. We may change this value if we wish, but it is just as well to leave it alone as it has no bearing on the user experience. This is also the name of the field as we will use it when we write custom code for our Webform.
Default value Under certain circumstances we may want to have a component pre-populated with data. All components that support this feature will have a Default value option on their respective settings pages. We are not limited to only those default values, we can type in other values ourselves. Webform also has support for a variety of token values (given as follows) that may be used to specify defaults.
Token values Tokens are basically placeholders that will be replaced by an actual dynamic value when the form renders, for example, the token %username will be replaced by the actual username of the logged in user. When we click on the TOKEN VALUES heading we see a listing of all the tokens that Webform supports. Note that a token name starts with a percentage symbol (%) which is immediately followed by the token name. Certain token names refer to a group of possible tokens, so we need to specify the exact field from the group which we want to use. This is achieved by naming the specific field by its key in square brackets immediately following the token name, for example, %tokenname[key].
Description There are times where we would like to explain to the end user what the purpose of a particular field is or what kind of information is being requested. Webform permits us to specify some explanatory text here which will display below the field when the form is rendered. Note that we may make use of token values (see the previous description) in this description.
22
Chapter 2
Validation The Webform module makes some basic field validation available to us. Users will be unable to submit a form if any one or more of these rules is broken by their attempted submissions. The field validations are as follows: ff
Mandatory: Check this box if a field absolutely must receive a value from the end user and may not be left blank. By default, if this setting is checked, the field label will be marked with a red asterisk to indicate that user input is required for this field.
ff
Unique: This is a useful setting for fields where no two form users may enter the same value, for example, e-mail address or passport number. We should exercise care when using this setting as we must be sure that it is a reasonable setting to apply. Imagine the frustration that would be experienced if we set this validation for a first name field for example.
ff
Maxlength: Here we can specify the maximum number of characters that users may enter into a field.
Display We have several options that can affect the manner in which a field is rendered on the form as follows: ff
Width: This setting defines the number of characters that will be visible in the text field.
ff
Label placed to the left of the textfield: It can be helpful to place an additional label to the left of a field to give the user an idea of the type of information required. For example, assume we have a field called Amount, we can enter a US Dollar symbol ($) here to indicate the currency type to the user.
ff
Label placed to the right of the textfield: Similar to the previous point, there are contexts where the descriptive label should rather appear on the right, for example, on a Weight field we may want to indicate that value entered should be in kilograms by specifying kg here.
ff
Label display: Field labels may be specified to be displayed above the input field, adjacent to the input field, or not at all.
ff
Disabled: Occasionally we may wish to show to our form users a default value that they may not change, such as their username token value. To make the field value non-editable we check this box.
ff
Private: Certain fields may be required for the use of form administrators, but do not require any form user input. By checking this box, only form administrators will have access to this field and it will not be shown when the form is rendered to non-administrative users.
23
Trying Out Webform
Operations After saving our component settings we find ourselves back on the Form components overview page where we see that the saved component now has three Operations links. The various operations are as follows: ff
Edit: The edit operation allows us to effect any changes we may need to make to the current settings of a component.
ff
Clone: When we find ourselves needing to create several components of the same type with similar settings, we will find our efficiency is improved by merely cloning (making a copy of) an existing component. All we need to do is specify the label and field key for the new component and click on Save component to create the new component.
ff
Delete: Allows us to remove existing components from our form. Following through on this action will also remove all data that has previously been submitted for this component by user submissions. Use with care as the delete action is not reversible!
Cloning components For the sake of uniformity in the presentation of our form we will clone the First name component to create a Last name component with similar settings.
How to do it... Cloning is the act of making a copy of something. Let's take a look at how we may copy existing components to save ourselves some work: 1. On the Form components overview page, click on Clone under Operations adjacent to First name. 2. On the new component's settings page we change the Label to Last name and change the field key to last_name. 3. Finally, we can click on Save component.
How it works... Cloning is a useful time saver when we need to have more than one component of a given type with similar settings.
24
Chapter 2
There's more... The clone operation makes a carbon copy of an existing component and requires us to specify at least a new field key for the new component. The new field key will allow the system to differentiate between the two components, that is, the original and its twin. The label may be left the same as the original component, but we must be sure that this will not confuse our form users. We would be well advised to assist our users to distinguish the fields by giving each component a unique label.
Adding e-mail components To assist with communication between form users and our conference organizers we will capture the e-mail address of registering speakers. The field will be a mandatory input and we will add a validation rule to ensure that no two speakers submit the same e-mail address. It is quite possible that registering speakers are already registered users of our website, so we're going to default the Drupal user's e-mail address into this field. Many people have several e-mail addresses that they use for different purposes and it is possible that the registered user's e-mail address is not necessarily the preferred address that the registering speaker would like correspondence being addressed to. For this reason we will leave this field as editable.
How to do it... Type e-mail address in the New component name textfield. Select e-mail in the TYPE dropdown selection list, check the box under MANDATORY and click on the Add operation button. In order to pre-populate this field with a logged in user's e-mail address, we must enter the user e-mail address token %useremail in the Default value text box. To ensure that no two registering speakers attempt to submit identical e-mail addresses we check the box next to Unique under the VALIDATION heading. Click on Save component to create the component and return to the Form components overview page.
How it works... While the form is being built for rendering, Webform will substitute the %useremail token with the e-mail address supplied when the user is registered on our site. The field will always be blank when the form user is not currently logged in. Notice that the user e-mail token is listed under the VALUE column of the components overview page.
25
Trying Out Webform
There's more... The e-mail component validates that e-mail addresses are correctly formed. It makes use of the same validation that the Drupal core system performs when users register on the site. This validation is not foolproof, however, because it does not verify that the specified e-mail server exists (that is, the bit that follows after the @ symbol in the submitted e-mail address), nor does it verify that the specified e-mail user (that is, the bit that precedes the @ symbol) exists on that e-mail server.
Viewing our progress Lets see how the form looks so far by clicking on the View tab, shown as follows:
We should see that the node title and description that we entered when creating our Webform node appear at the top of the form. Our three components are listed underneath, followed by a form Submit button. Okay, let's click on the Webform tab to continue adding components.
Adding textarea components We need to gather some information from speakers regarding the presentation they plan to deliver at our conference. Organizers have specified that the presentation title may not be longer than fifty characters and is a required field. Organizers also need a brief synopsis of the content of the presentations for inclusion in marketing material. 26
Chapter 2
How to do it... 1. Add a new mandatory textfield component named Presentation title. 2. On the settings page, set the Maxlength property to 50 and save the component. 3. Add a new mandatory textarea component named Synopsis. 4. In the Description text area on the settings page for the textarea, we enter the following descriptive text before clciking Save component: Please provide a clear and concise summary of the content of your presentation and save the component.
How it works... These two new fields on our form enable the registering speakers to name their presentations and give us a brief summary of the content. The Maxlength setting on the Presentation title field will prevent users from submitting a title of more than fifty characters. This is achieved by the user's browser limiting the number of characters that can be typed within the textfield.
There's more... The textarea component type creates a rectangular box that accepts free-format input. While it is similar to a textfield in many respects and has many of the same configuration setting options, it differs from the textfield. Textarea makes more than one line of text possible to the end user. An additional setting we have for this component, which is not present for a textfield, is the Resizable option. When this box is checked the user will be able to drag the bottom right-hand corner of the textarea to change its on-screen size.
Adding fieldset components Now that we have two distinct groups of input fields on our form, that is, speaker personal information and presentation information, it would make our form more organized if we had a way to clearly separate the two groups of fields. HTML (Hypertext Markup Language) enables field grouping by means of fieldsets. We're going to add two fieldsets to our form to improve the organizational layout of the form by separating our input fields into their respective groups.
27
Trying Out Webform
How to do it... 1. Add a new fieldset component named Speaker Details and just accept the default settings by saving the component. 2. Add and save another fieldset component named Presentation Details. 3. Now we're going to drag each input field into its respective fieldset by grabbing the drag handle (the cross-shaped symbol with arrow heads on the tips) that appears to the left of the component label on the components overview page as follows:
28
Chapter 2
4. Position the mouse pointer over the drag handle next to First name, hold down the left mouse button and drag the field down immediately under the Speaker Details fieldset component. 5. Move the mouse pointer slightly to the right so that First name is indented somewhat and release the mouse button:
6. Let's repeat the process for Last name and Email address also, positioning them just below First name and similarly indented. 7. Drag and drop the Presentation title and Synopsis fields into the Presentation Details fieldset. 8. As the warning message indicates, the repositioned field sequences will not be stored until we click on the Save button, so let's click that now.
29
Trying Out Webform Our properly organized components overview table should now look like the following screenshot:
How it works... The grouping of fields operates on the principle of parents and children. The component that contains other components is the parent component. All components on the form are children elements of the form itself. These fieldsets are children of the form, but parents of the components they contain.
There's more... A neat trick with fieldsets that Webform exposes on the fieldset configuration page is collapsible fieldsets. This setting turns the fieldset name into a clickable link, which when clicked, will either expand the fieldset so that all of its child fields are visible or collapse the fieldset and hide all of its children, depending on the current mode of the fieldset. To enable this functionality we need to check the box adjacent to Collapsible. We can also specify that the fieldset should initially be collapsed when the form first renders by checking the Collapsed by Default box.
30
Chapter 2
Theming components via Cascading Style Sheets We can make use of our Drupal themes Cascading Style Sheet (CSS) files to make the fieldsets stand out more prominently on the form. Most theme CSS files will have entries for fieldsets and their legends (a legend is the CSS/HTML property that relates to the name we gave to our fieldset component). We can also specify a different color or thickness for the fieldset border. All of the components may be similarly custom-themed if we so desire. If CSS is something unfamiliar to us, then we can work through some of the many excellent tutorials that are available online to discover just how much power this gives us in terms of the final presentation of our form. We may also refer to Chapter 7, Theming Webform where we cover the adding of customized CSS rules. When we make changes to our theme CSS files we may need to clear the website caches to ensure that our changes take effect. This can be done by clicking on Configuration | Performance | Clear all caches.
Adding select components It is customary to use people's titles in salutations in correspondence. To enable this on our form we're going to set up a drop-down list of titles for our speakers to select from.
How to do it... 1. On the components overview page, drag the empty component row up to just above First name in the Speaker Details fieldset. 2. Add a mandatory Select options component with the name of title. 3. In the required Options textarea on the settings page, let's enter the following options, each one on its own line. Note that the pipe, that is, the vertical line separating the entries on each line is often found on the backslash key (\) on the keyboard: Mr|Mr Mrs|Mrs Ms|Ms Dr|Dr Prof|Prof Hon|Hon Rev|Rev
4. In the Display section of the settings we need to check the Listbox option before saving the component.
31
Trying Out Webform
There's more... The options as we have entered them previously tell Webform two things about each option. The first section to the left of the pipe separator is the internal key associated with an option, while the text to the right of the pipe separator is the option text that our form users will see. Each option must be placed on its own line so that Webform can accurately determine how to handle each option. The Select options component type is one of the most complex and flexible of the Webform components. It permits us to create single-select drop-down lists as we did previously, radio button lists which will allow only one selection to be made from a list, multiple-select checkbox list, or multiple-select drop-down lists. As daunting as this may seem at first glance, the functionality is quite logical in its implementation and we'll cover the other variations as we develop our form.
Phase one complete This is as far as we're going to go in terms of adding components to our form right now. In later chapters, we will develop the form further. Let's click on the View tab to see what we have created thus far:
32
Chapter 2
The basic version of our form is ready for testing. Before we do test it though, let's configure a reply e-mail that will be sent to users who complete a successful submission.
Configuring a reply e-mail Our imaginary conference organizers have requested that we send an acknowledgement of registration to all speakers who register via our Webform. Luckily, Webform has a built-in facility for us to easily do so.
Getting ready We were busy admiring our handiwork on the View tab. Let's now click on the Webform tab to return to the components overview page.
How to do it... To configure an automatic e-mail we need to click on the E-mails subtab that is just below the Webform tab.The first e-mail configuration screen enables us to specify the intended recipient of the e-mail: 1. We're setting up an e-mail to be sent to the person registering on our form, so we will select Email address from the drop-down list next to the Component value: entry and click on Add. 2. On the Edit e-mail settings page we will leave most of the defaults as they are. We will alter the standard e-mail template by selecting Custom Template under the E-MAIL TEMPLATE heading and changing the template to look like this:
33
Trying Out Webform 3. After we've checked that we have the token names correctly set up we can save our custom e-mail by clicking the Save e-mail settings button at the bottom of the page.
There's more... We could, if needed, configure another automatic e-mail to be sent to one of the conference organizers upon each successful submission. One obvious change we would need for our first e-mail is the recipient address under E-mail to address. For completeness we could also change the e-mail sender address under E-mail from address to be that of the person registering. A close look at the e-mail configuration page shows us that we can customize every aspect of the e-mails that get automatically generated. We may even specify only those components whose values are required in the e-mail. By default, all components will be included. A Drupal contributed module that is very useful is the MIME Mail module (http://drupal. org/project/mimemail). With this module installed and active, all e-mails sent from our site are sent in HTML format and can be styled as per our current site theme, can contain embedded images, and may also have attachments. See the project home page for installation details.
Testing our Webform One aspect of form development that is often either overlooked or not always thoroughly done is the testing phase. While testing can consume a little time, the savings in the long term can be immense, in terms of both time and reputation. The testing phase is where we get to identify and repair any little cracks or gaps that may have crept in between the original specification and the actual implementation. But it must be done thoroughly. If testing is not properly done before the form is live and published, then our form users become our testers, which is not fair on them. It is better by far if the problems, niggles and irritations are discovered and handled internally before we cause frustration out in the public domain. While a certain amount of technical testing is necessary on the part of the form developer, it is best if someone other than the form developer does the usability testing. The main reason for this is that the developer is going to see what they expect to see, whereas another user who was not as intimately involved in development is more likely to accurately measure what they see against the original wish-list from the form design stage. These users will also be better placed to evaluate the form in terms of usability.
34
Chapter 2
In the case of forms more complex than our current form, it is almost never good enough to have one person do one test submission and consider the job of testing to be done. As the options on the form multiply, so do the number of potential test paths, so we should ensure that the test plan covers as many of these possibilities as is practical. Something else to consider in the set up of the testing plan is the various validations that we specified for components, for example, unique e-mail addresses.
Getting ready The person or preferably persons who are going to conduct the testing should familiarize themselves with all of the form requirements as per the design discussions. From these they can draw up a checklist of specific items to be checked off as they progress through the form.
How to do it... Thankfully our form is still fairly simple, so all that needs to be checked is that the mandatory fields are, in fact, enforced and that the same e-mail address cannot be submitted multiple times. The form should be tested at least once as an anonymous user (that is, by a user not currently logged in on the site) and once as a registered user. This is to ensure that the %useremail token substitution works as expected. We should also include in our test plan to see whether we can enter more than fifty characters in the Presentation title field, or whether we are blocked from doing so, as per the rule we set up on the component. We should ensure that the confirmation e-mail arrives at the specified e-mail address and that it is in the layout we set in the template.
35
Trying Out Webform Just clicking Submit on the blank form is the easiest way to test the mandatory fields. Let's click on the View tab to load up the form and then click the Submit button. We should see all the mandatory field error messages at the top of the form display highlighted in a red box as follows:
Notice the red highlighting of input areas on the form itself which serves as an aid to identify the fields in error. Let's now assume the role of testers and enter some test submissions, taking into account the testing actions described previously. Please enter several test submissions so that we have enough data to play with in Chapter 3, Working with Submissions where we see what Webform offers in terms of working with submitted data.
36
3
Working with Submissions In this chapter, we will cover the following topics: ff
Viewing submissions metadata
ff
Viewing submissions
ff
Editing submissions
ff
Analyzing submitted data
ff
Downloading submissions
ff
Deleting submissions
ff
Clearing the database
ff
Changing Webform results defaults
Introduction Software systems dealing with persistent data storage, such as Webform for example, generally adhere to a basic pattern of functionality known by the acronym CRUD: C—Create new data to be stored R—Read or retrieve data that has been stored previously U—Update data that has been stored previously D—Delete or destroy previously stored data that we no longer have use for
Working with Submissions Apparently first coined by a chap called James Martin in his 1983 book entitled Managing the Data-base Environment, CRUD has long been the minimum standard set of functionality for both database management systems as well as the user interface of many computer applications, from personal contact managers through to word processors and spreadsheet software. Wikipedia has a neat overview of the topic at the following URL: http://en.wikipedia.org/wiki/Create,_read,_update_and_delete with links to
additional topics.
In the context of Webform, the first of these functions (creating data to be stored) is handled by the form that we put together and tested in Chapter 2, Trying Out Webform. When our form users fill out the form fields and submit the information, they effectively create a new set of data in our Webform database. The remaining three CRUD functions (read, update, and delete) are, of course, available in Webform. By default, access to these functions is limited to those users and roles who have been granted the appropriate permissions as discussed towards the end of Chapter 1, Setting up Webform. On a fresh Webform install, only the site superuser has access permission. In the general case, we will find that access to these data manipulation functions is reserved for various levels of site administrator, that is, known and trusted users. Any time that we are requesting personal information from our site visitors and form users, we assume the burden of responsibility for the safekeeping of that information. It is wise to be selective about who is granted access to this data. Clearly, before we can effect changes to the submitted data, we first need a method to locate the data that requires changing. This type of activity falls under the R of CRUD—reading or retrieval of data. Once the required set of data has been found, we can then carry out one of the two remaining CRUD functions as desired—either make some changes and update these to the database or delete the data set. Let us now get a handle on how Webform implements the read, update, or delete parts of the CRUD application design pattern.
Viewing submissions metadata Metadata is a computing term which means data about data. Apart from storing the actual data and bits of information submitted by our form users, Webform also stores information about the submission itself depending on the following cases: ff
When the data was submitted
ff
The user who submitted the data
ff
Where the data was submitted from
38
Chapter 3
Getting ready To make these exercises meaningful we will require an existing Webform where some data has already been submitted. In Chapter 2, Trying Out Webform, we built a Speaker Registration form and entered a few test submissions, so this is the form used in the examples that follow. Due to the security implications of working with our form user's information, which is often personal to some degree, we also need to ensure that we are logged in to our site as a user that has the necessary Webform data access permissions.
How to do it... Let's navigate to the Speaker Registration form we created in Chapter 2, Trying Out Webform and then click on the Results tab. By default, we are presented with a table listing the metadata of all submissions that have been made on our Webform.
How it works... In the preceding table, we see a summary display of the number of submissions that have been made on our form. When our form gets very busy and attracts a large number of submissions, this summary line will be expanded slightly to allow us to select the number of submissions that should be listed on this page at one time. Along with this, we'll also see links at the bottom of the page to facilitate paging forwards and backwards through the submissions list once the total number of submissions made on the form is greater than 20.
39
Working with Submissions Every submission that is made is assigned its own unique number, known in Webform as the submission ID. The submission ID is automatically incremented per submission, regardless of which Webform the submission was made on. When we have more than one active Webform on our site we will notice that the submission IDs do not appear to be sequential, that numbers are being skipped. We need not worry, as we will find those missing numbers in the submissions listings of our other forms. The date and time that the form was submitted is determined by the system clock of the server hosting the website and is expressed on screen according to your Drupal installation regional time zone and display format settings. Should a form be submitted by a logged-in user of your site, the username will be listed in the USER column, otherwise the user is declared Anonymous, that is, unknown. In the case where a submission was made by a registered user, the username will be displayed as a hyperlink that links to that specific user's profile page. The last bit of metadata presented is IP ADDRESS of the user making a submission. Individual computers and, in some cases, individual networks have numbers assigned to them that are used by the Internet Protocol (IP) to identify the source (address) of Internet traffic. The IP address can be a very useful piece of information to have. For example, analyzing these addresses could help us determine which country networks, even down to company networks, our forms attract the most traffic from. Under the OPERATIONS column, we find links enabling us to perform one of the CRUD functions on the corresponding submission in that row.
There's more... The core Drupal system contains functionality that is automatically available to the contributed module programmers and helps to ensure a consistent user experience by standardizing various aspects of the user interface.
Sorting tables On pages that display table listings, such as the submissions overview page we are currently looking at, we will see that some table headings are rendered as hyperlinks. These headings, when clicked, will re-order the table contents based on the values contained in that column. When we first came to this submission overview page, the table contents were sorted in descending submission ID sequence, as indicated by the downward pointing arrow in the submission ID column (marked by #). Then, the default listing shows the most recent submission in the top row of the table, whereas the earlier submissions are further down the list.
40
Chapter 3
To rearrange the listing in ascending submission ID sequence, all we need do is click on the # column heading—the page will redisplay the data in ascending sequence and the little arrow will point upwards to indicate that fact. This particular table is sortable on submission ID, submission date and time, username, or IP address columns. To alternate between ascending and descending sequence, we just click on the relevant heading a second time.
Viewing submissions The CRUD functions in Webform are closely related. Suitably authorized administrators will ordinarily find the corresponding Webform modes (Read/Retrieve = View, Update = Edit, Delete) grouped together, either as links or as tabs towards the top of the page.
How to do it... Selecting any one of our test submissions at random, let us click on the View link in the OPERATIONS column.
41
Working with Submissions
How it works... Webform makes use of the submission ID of the selected submission to retrieve all the related data from the database. Once all the data is to hand, Webform renders a facsimile of the form we designed. Typically the field names are rendered in bold text with the corresponding submitted data underneath in the normal theme font weight. When working with submitted data in either View or Edit mode, the form layout is preceded by the submission metadata in the box entitled Submission information. Following in the very sound design and engineering tradition of POLA (the Policy/Principle Of Least Astonishment—meaning, in this case, that every effort is made to have users see what they expect to see), Webform renders the submitted data view based on the form design and component sequence. We notice, for example, that even our grouped field sets are defined by a neat box. Because we are currently in the View mode, the data is not editable.
There's more... Another manner in which Webform adheres to the traditions of POLA (meaning, in this case, presenting users with a consistent interface) is that similar functions are available while in either View or Edit mode.
Paging through submissions We have the facility to page through our form submissions one at a time. Paging back and forth is achieved by clicking on the Previous submission and Next submission links we see at the top right and bottom right of the form display above. When these links are clicked, Webform will display the next submission in the specified direction.
Resending e-mails There will come a time when we need to resend the automatic e-mails we configured for our form. For example, the user may have accidentally deleted their e-mail and has requested a new copy, or some data was changed and we wish to send confirmation of this to the form user. We can achieve the resending of e-mails on a per-submission basis by clicking on the Resend e-mails link at the top left of the page. We use plural for e-mails because, if you recall from the e-mail configuration exercise in Chapter 2, Trying Out Webform, we may set up more than one e-mail in our form configuration. In the case where we have multiple e-mails configured, Webform gives us the ability to specify which e-mails we wish to resend.
42
Chapter 3
Viewing multiple submissions There is yet another option for viewing the submitted data, one which can be more useful than the submissions overview page when the majority of our submissions are from anonymous users. Identifying a specific anonymous submission is almost impossible from the data available to us on the submissions overview page. Unless we know the exact date and time of the submission, or know for certain the unique IP address that the submission came from, we would have to page sequentially through all of the submissions until we locate the one we are looking for. Thankfully, however, Webform also offers us a spreadsheet view of the submitted data, which enables a faster data browsing experience. While on the submissions metadata overview page, we can click on the Table tab to see a listing of our submissions as well as the data that was submitted.
43
Working with Submissions
See also The recipe Changing Webform results defaults discussed in this chapter.
Editing submissions As explained previously, the Webform name for the Update function in CRUD is Edit. This is the function that permits us to make some change to the data that was previously submitted and to store the changed data in the database.
Getting ready One of the three routes to editing submitted data is to click on the Edit tab while in the View mode. Another route is to go back to the submissions overview page and to click on the Edit link in the OPERATIONS column for the submission. The third and final route we can follow is to click on the corresponding submission ID (which launches the View mode for the submission) while in the Table view mode and then click on the Edit tab. Let's get ourselves ready to edit one of our test submissions by following one of the preceding routes to get into the Edit mode on a particular submission, it does not matter which one.
How to do it... Editing a submission is similar to making a new submission from scratch, except all the fields already contain the information that was previously stored. Let us make a small amendment for now and just change our selected registered speaker's title to Doctor (Dr). When the selection has been changed, we update the database with our amendment by clicking on the Submit button.
How it works... Webform makes use of the submission ID of the selected submission to retrieve all the related data from the database. Once all the data is to hand, Webform renders the form and populates all the fields with the previously stored values. We are free now to bring about any required data changes and afterwards store the amended data in the database by simply submitting the changed form. The fact that we are logged in as an empowered user does not give us the ability to break any of the configured validation rules, however. Required input fields remain mandatory that is, they (may not be left blank) and any uniqueness validation will still be enforced. As happens with a regular user, Webform will not accept any data that fails validation. We will be shown the same kind of error messages as are presented to regular users should we be in breach of any validation rules. 44
Chapter 3
There's more... Considering how far-reaching the effects of data changes can be, we are well advised to bear the following points in mind when editing the submitted data.
Resending e-mails As a minimum, it is polite to let a user know when we make changes to their data. Depending on the context of our form, the changes we have made may even have legal, financial, or other implications that the user (or registered speaker in our example) should know about. It is also entirely possible that other administrators need to be made aware of these changes to avoid inconveniences and possible catastrophes down the road. To ensure that everyone is on the same page, so to speak, we should now click on the Resend e-mails link at the top left of the page and allow Webform to communicate our activity to everyone concerned by clicking on the Resend e-mails button.
Updating data Webform does not, in point of fact, update data at all. What happens under the hood when we submit an edited form is that all traces of the previous version of data are physically deleted from the database. After the existing version has been deleted, Webform stores the new version of data we have submitted. It may seem a grossly inefficient way of going about things, but it is the only way to ensure that submissions do not get corrupted, particularly on forms that contain multiple-select components. For a variety of technical reasons, Webform does not, in native state, store submission histories. When changes are made to a submission, the previous values are forever lost. Gone. For good. At any one time, all we have is the current version of a submission. Journaling, that is, the process of storing historical versions of data, is excluded from the Webform functionality because it creates a lot of database overhead. This particular weakness in Webform is brought about by one of the Webform's greatest strengths—its flexibility. To get some idea of why this is, the curious among us may read through the next few paragraphs. Those of us who are happy to accept the status quo are welcome to skip ahead past the technical stuff to the next recipe, Analyzing submitted data. In order for us to have forms which are dynamic, where fields can be added, removed, or changed at will, where data types can vary from single entry inputs to multiple, it is necessary to implement a non-standard underlying database approach to data storage. While it appears that Webform stores data in a normal table where each field has its own column and each submission is stored as a single row of information (for the non-technically minded—similar to a spreadsheet layout), the reality is quite different.
45
Working with Submissions Some component types permit more than one input value. An example of this is a Select options component where multiple-select may be permitted. Another example is the Grid component which we will have a look at in the next chapter. Going back to the example of a spreadsheet, these components would require one spreadsheet row to contain multiple cells of data within a single cell in the columns relating to these multiple-value components. This is, quite simply, not achievable. A person with some relational database experience may be tempted to offer a solution regarding linked tables. This is an aspect of relational database design where one can, effectively, link two spreadsheets by some relationship, for example, a shared index or pointer. The idea here would be to have our main spreadsheet (or table) row contain a pointer to a group of related rows in a secondary spreadsheet (table) which houses the multiple values. This is not a bad idea, in fact it is a very good idea, but not in the context of Webform. To implement a storage strategy as just described would require Webform to perform many, many queries on the underlying database (for example, MySQL, PostgreSQL). Tables would need to be created, dropped, or re-indexed on the fly. Table columns would need to be added or removed dynamically. Join queries would need to be dynamically built and modified as the form configuration changes. All of these activities would severely degrade the user experience as they would soak up a lot of processing time, let alone processing power. To get around these challenges on the basis of exchanging a lesser evil for the greater good and convenience of the greatest number of situations, what Webform actually does is store each submitted fields, data in its own row in one single table. This table, called webform_submitted_data in our Drupal installation's underlying database, stores the pertinent node ID (the number that Drupal assigned our new piece of Webform content), the relevant submission ID, the associated component ID, a data value sequence number (for use by those components that permit more than one input value) and, finally, the actual data value. The storage strategy adopted by Webform is not so much the most efficient of all possible options as it is the least inefficient. The motivation is to retain as much flexibility as possible, for as many potential use cases as possible, without making the system unbearably slow. Unfortunately, there are trade-offs. Arithmetically, a form with 100 fields, of which ten fields permit up to ten multiple values each will store around 200 records per submission. A relatively busy form may receive 200 submissions, which takes us to 40,000 records on our table. When we factor in, arbitrarily, an average of three amendments per submission we rapidly approach 1,20,000 records for the database engine to contend with. Now let us factor in five concurrent active users on the form. The web server is clearly going to be stressed to satisfy all the demands being made upon it. Contributed modules do exist which can implement the data version control which Webform lacks. We must be aware, though, that we may compromise the responsiveness of our forms by enabling such functionality. 46
Chapter 3
See also The section entitled Tracking changes to submissions in Chapter 11, Presenting and Managing Data, introduces a contributed module which enables us to store historical versions of submitted data.
Analyzing submitted data All of the Webform input components provide a basic analysis of input received. This is a handy feature that gives us a quick analytical overview of the content of submissions received thus far. Expressed differently, we have access to summarized metadata based upon the inputs and selections of the submissions in our database.
How to do it... To see what the built-in analysis of the submitted data reveals, we need to navigate to our forms, Results tab and then click on the Analysis sub-tab.
47
Working with Submissions
How it works... As we have come to expect, the analyzed component data is shown in the same sequence as our Webform renders the components. The type of analysis on a particular component is driven by the type of data the component stores. Select option component types, such as our Title field, will list all of the available options in conjunction with a count of the number of times each option has been selected among all of the submissions received to date. Text input components, such as our textfield component First name and our textarea component Synopsis, will show us how many submissions have left this field blank, how many have included a value for the component, and finally, an average word count calculated from the submissions where the submitted value is not blank.
Downloading submissions As powerful as the Webform module undoubtedly is, it cannot hope to solve all of our varied and individual data usage needs. When we have reached the limit of what Webform offers, we download the data in spreadsheet format to continue. Once we have downloaded the submitted data we may use the resulting spreadsheet with our preferred spreadsheet application to achieve other ends, such as creating a mail-merge document to print conference name badges or producing graphs, for example.
Getting ready Importing the submitted data into our preferred spreadsheet application is as easy as clicking on the Download sub-tab on our Results page. Of course, we do need to be logged in as a user with Access all webform results permissions enabled in order to have these options visible.
48
Chapter 3
How to do it... There are several options we may use to define our download request parameters, but for the moment we will accept the default settings: 1. Let's click on the Download button. 2. Most Internet browser applications will now show a pop-up which allows us to either open the downloaded file directly, or to first save the file to our computer, before we open it with our spreadsheet application software. Let us select the option to open the file.
49
Working with Submissions 3. While most spreadsheet applications can import data in a variety of formats, they do tend to expect the file to be in a special binary format. Webform exports data as a flat text file, using special characters to separate columns (that is, fields), with each spreadsheet row on its own line. Our spreadsheet application will now ask us to confirm that it has correctly identified the column separators and we click on OK to proceed with the import.
4. To ensure that we get full value from our spreadsheet application, let's now save the spreadsheet to our computer in the standard format for our software, for example, as .xlsx for Microsoft Office Excel or .ods for Calc (OpenOffice.org and LibreOffice).
How it works... By accepting the defaults on the Download page, we now have a spreadsheet listing all of the submissions made on our form. The data is sorted in submission ID sequence and we see our component names, or labels, as column headings.
50
Chapter 3
The first few columns show us the familiar metadata for each submission, after which we see the submitted data for our form components in the same sequence that they render on the form, although now expressed from left to right in the same row.
There's more... Let's take a quick look at the various options on the Download page and learn how they influence the downloaded data file.
Export format As the submitted data is exported in text file format, we need to tell Webform how our spreadsheet application knows where one field's data ends and the next one starts. We achieve this through defining the limits of each cell by means of a specified character known as the delimiter. It is important to note that we must select our delimiter with some care, as otherwise our spreadsheet import could give us unexpected results. Selecting a comma as the delimiter would work only if we are assured that there can be no commas in the submitted user input. If commas are present in the submitted data, we will find that our spreadsheet software will split one field's data across two or more columns, depending on the number of embedded commas in the data. In the general case, therefore, it is safest to use the default tab delimiter. The pipe (a vertical line) is also a fairly safe option to use.
Select list options When we define a Select Options component, such as our Title field from the form built in Chapter 2, Trying Out Webform, we specify two values per option on the component settings page—the internal key and the human-readable screen value. In this option set, we may specify which of these two values is preferred for the data download. Additionally, we may specify whether the various selections per component should be listed each in their own column or concatenated together in a single spreadsheet column.
included export components It is not always required for us to download all of the submitted data. On those occasions where only a few of the form fields are required, we may uncheck the fields we do not need.
51
Working with Submissions Should we decide, for example, that we require a list containing only the registered speakers' first and last names, we could uncheck the INCLUDED ALL COMPONENTS option and check the boxes adjacent to First name and Last name.
To exclude only the submission metadata section from our download file, we would, intuitively, uncheck the box at Submission information.
Download range options Just as we do not always require all fields to be included in a download, we may also wish to download only a specific set of submissions. By default we will download all submissions, but we may reduce the downloaded data set to only those submissions that have come in since our last download. The other options are to download only the most recent number of submissions or submissions where the submission ID falls within a specified range.
Deleting submissions The final set of functionality required by the CRUD design pattern is the facility to delete (or destroy) data.
52
Chapter 3
Getting ready As with editing, there are three routes to deleting submitted data. One method is to click on the Delete tab while in the View mode. Another route is to go back to the submission's Overview page and to click on the Delete link in the OPERATIONS column for the submission. The third route we can follow is to click on the corresponding submission ID (which launches the View mode for the submission) while in the Table view mode and then click on the Delete tab.
How to do it... Let's get ourselves ready to delete one of our test submissions by following one of the preceding routes to get into the Delete mode on a particular submission: 1. When we click on Delete, we are immediately confronted with a confirmation screen. If we are certain that we wish to permanently remove the submission from the database, then we may click on the Delete button, otherwise we can gracefully back out of the action by clicking on Cancel.
How it works... In Webform, as is standard across all Drupal modules, any delete action is permanent. There is no undo button to bring back what we have discarded. We need to be absolutely sure, before we irretrievably lose data, that we have selected the correct submission for deletion.
Clearing the database Normally, after a form has been thoroughly tested, we will have several submissions in our database that we need to get rid of. While we could delete these one at a time, a more efficient route is to merely clear the database of all submissions pertaining to a form. We may, of course, also follow this route if we wish to re-use a form.
53
Working with Submissions
How to do it... When we are certain that we no longer require the data we may clean out the database. 1. After clicking on the Results tab, click on the Clear sub-tab. 2. In a similar fashion to delete submissions, Webform presents us with a confirmation screen where we can either confirm that we wish to continue with the bulk delete action by clicking on the Clear button or we can return to safety by clicking on Cancel.
How it works... This action will permanently remove all data submitted for the current Webform, with no possibility of restoring what we have discarded. Depending on the importance of the data, we may want to first obtain a full download for record-keeping prior to clearing the database.
Changing Webform results defaults The purpose of this exercise is to demonstrate the basics of creating our very own custom module to change the way Webform does things. Later on, when we get to creating our own custom components and so forth, we will build on knowledge gained in this relatively simple project. What we'll be doing here is changing the default Results tab view from the Submissions overview to the full submission Table view. As we noticed in the preceding exercises, the Submissions overview is not very helpful when the majority of submissions received are from anonymous users. Our intention is to save our data administrators a click or two by having Webform show the full submission data listing when they click on the Results tab. While we're busy, we will also be re-arranging the sub-tabs on the result page so that the more frequently used items are towards the right and we'll be changing the Table sub-tab to read Database instead.
54
Chapter 3
Non-coders may happily skip the remainder of this section if they so wish. Those of us who will be following along here should note that this is not a definitive guide to creating Drupal modules. It is a simplistic and introductory venture into the world of custom coding for Drupal 7 modules using a standard API (Application Programming Interface) hook, hook_menu_alter. Some knowledge of the PHP programming language syntax is assumed.
Getting ready All we need to create our custom module is a text editor and some method of copying files to the server hosting our Drupal website.
How to do it... Drupal modules each reside in their very own folder and the folder is given the same name as the module. 1. Let's create a folder named webform_custom to house our custom module files. 2. Within this new folder we'll be creating two files for our custom module to be properly recognized by the Drupal system. 3. Using our favorite text editor, let us open a new empty file, enter the following code, and save the file as webform_custom.info. name = Webform Custom description = Customize Webform Results page. core = 7.x package = Webform dependencies[] = webform
Downloading the example code You can download the example code fles for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub. com/support and register to have the fles e-mailed directly to you.
4. The info file introduces our module to the Drupal system. The name and description we have given previously will be displayed on the Modules page when we go to enable our custom module. The line commencing with core stipulates that this module may only be enabled on a Drupal 7 website. 5. The last two lines tell Drupal that this module is an extension of the Webform module and Webform must already be enabled before this module may be enabled. Should we wish to disable Webform at a later point in time, then this custom module of ours will need to be disabled first, because Drupal will not allow us to disable a module on which other modules depend. 55
Working with Submissions 6. Now for the bit that does the actual work. Let's open a new empty file in our text editor and save the following code as a file named webform_custom.module. PHP tag. This is not required by the PHP parser and its presence can cause problems in a system as complex as Drupal.
7. Internally, the Drupal menu system is driven by an associative array called $items. All we're doing here is changing a few of the menu items that apply to the Webform Results page. 8. In the first four lines of code we're substituting the full data listing for the submissions overview page as the default display when the Results tab is clicked. 9. The next line of code causes the sub-tab Table to be renamed as Database. A standard within Drupal is that items are sequenced according to their weight—a lower weight floats towards the top and a heavier weight floats towards the bottom. In the last four lines, then, we are changing the display sequence of the sub-tabs on the Results page. 56
Chapter 3
10. Just as we did when we installed the Webform module, we need to copy our module folder (with the two files we just created) into our Drupal installations folder /sites/ all/modules. 11. To enable our module, we must navigate to the Modules page on our menu bar, scroll down until we find our module, check the box to enable it, and then click on the Save configuration button.
How it works... The Drupal system scans through the /sites/all/modules folders looking for the .info files with corresponding .module files. These are then listed on the Modules page. Thanks to the pluggable modular design, Drupal allows us to make changes to various behavioral and display aspects via the hook system. We have used hook_menu_alter to effect a change in the way that the Webform Results page behaves. Where the Results page menu used to look like similar to the following screenshot:
It now looks similar to the following screenshot:
The concepts we have covered in this simple example will be reinforced when we encounter the Webform API, which exposes a set of hooks all of its own that we may use to manipulate Webform behaviors.
57
4
Discovering More Components In this chapter, we will cover the following topics: ff
Adding a page break component
ff
Adding a markup component
ff
Adding a hidden component
ff
Adding a grid component
ff
Adding a date component
ff
Adding a time component
ff
Adding a file component
ff
Enhancing component descriptions with HTML
Introduction In this chapter, we'll deal with the remaining components that Webform offers. Before we discover the additional components, let us consider the one component that Webform does not offer. The HTML standard makes provision for an input type called password. Folks with some HTML background may have looked at the list of components we have yet to handle and be wondering why there is no mention of a password component type.
Discovering More Components For the benefit of those who do not know what this is, the HTML password input type normally renders as a textfield and masks whatever is typed into it with asterisks. For example, if we were to type mypassword into such a field, what we would see on screen within the textfield is a string of asterisks like this **********, just as we see when we fill out our password to log in to our site. This input type has been intentionally omitted from Webform as it creates a false sense of security. The only real benefit of using this input type is to help prevent shoulder-surfers (that is, people who peer over our shoulders to try read our passwords as we enter them) from getting any useful information. There is absolutely no encryption of the data when it gets sent from the computer of our site visitor to our web server. The text that was entered into this field is sent unchanged (that is, as plain text, or in the clear) and is therefore susceptible to interception by malicious Internet traffic sniffers. This may be mitigated by hosting our site under an SSL (Secure Socket Layer) certificate, which will ensure that all communication between the client computer and the server is encrypted and is therefore reasonably secure. An even more important reason for its exclusion, with or without an SSL certificate, is the overhead around the responsibility of handling and storing passwords in the database. It is extremely insecure to store a password in plain text, they always need to be encrypted in some way prior to being stored. Once they have been stored, there are additional security issues to consider, such as who should be permitted to change these passwords and who should be entitled to see them. After we have determined permission rules around access to the information, we still need mechanisms in place to securely effect the access and changes. All things considered, a password management system is just too much to include in an information gathering interface, which is all that Webform purports to be. It is very tempting, for example, to try to utilize Webform to gather information from a site visitor and automatically create a new Drupal user on our site based on the submitted information. In such a case, we would probably want to make use of the input masking that the HTML password input type makes available, so that the visitor can let us know what their desired password should be. While it is certainly possible to do so, such functionality will not be made available by the Webform module, as it falls well outside of the scope of the type of situation that Webform is designed to help us handle.
Adding a page break component Throughout this chapter, we will be adding components to the Speaker Registration form that we started with in Chapter 2, Trying Out Webform. Then, we saw how the usability and readability of our form can be improved by grouping related fields into separate and distinct fieldsets. Webform offers us another layer of grouping by allowing us to break the form up into separate pages. Not only can we group related fields, we also have a mechanism for grouping related sets of input fields. This helps us focus our site visitor's attention on a select group of related inputs at one time.
60
Chapter 4
Getting ready Seeing how we're back in the mode of adding components to our example form, we need to ensure that we are logged in to our site with the Edit Webforms permissions and have clicked on the Webform tab of our form to reach the components overview page. For our ease of use, we should log in as the main site administrator to avoid any permission issues.
How to do it... We are about to see how easy it is to create a multipage form. 1. Let's give our page break component the name Page 2 by entering that in the textfield that contains the text New component name. Select pagebreak in the component type list and then click on the Add button. 2. There are no additional settings required for this component (apart from the mandatory label and form key fields which are already filled out for us), so we merely save the page break component by clicking on the Save component button.We see now, on the components overview page, a dotted line indicating the location of our page break, with the page break component name in a bold font weight.
How it works... When we previously viewed our form in Chapter 2, Trying Out Webform, we saw a button towards the bottom of the page that read Submit. Let's right-click on the View tab and open the page in a new window or browser tab to see that the button now reads Next Page >.
61
Discovering More Components Webform renders all components from the top of our components list until either reaches the end of the list or finds a page break. After the fields on the page have filled out, we click on Next page > to move on to the next group of input fields. On the final page. the button text will read Submit again, while intermediate pages will also have a Previous Page button which enables the user to step backwards through the form. Note that Webform will not permit us to move to the next page if any validation errors arise on the current page. We will have to correct our input before we may proceed to subsequent pages.
Adding a markup component Apart from the descriptive text that we may enter for specific components, we will occasionally want to insert a larger body of text, perhaps with a greater degree of HTML output formatting, as explanatory text on the body of the page. The markup component allows us to do just this.
How to do it... 1. Let's create a new component named Page 2 Header text. 2. Select Markup as the component type and click on Add. 3. Enter the following HTML code into the Value textarea and click on Save component: Page 2 of 2
Please answer the survey questions below as accurately as you can.
62
Chapter 4
How it works... HTML is an example of a Standard Generalized Markup Language (SGML) based language and is concerned, primarily, with expressing how information should be presented or laid out. In the preceding code, we have requested that the page number should be expressed in heading size 4 (the lower the number, the bigger the font size as an indication of importance) by enclosing it within the tags. The next sentence is defined as being part of a new paragraph by the
tags. The tags that enclose the word accurately indicate to the web browser that it should display in italics. Those of us unfamiliar with HTML would profit from the many HTML tutorials that abound on the Internet for further information on the myriad possibilities available. In most web browsers we may simply right-click on a web page and select View Source to see the HTML that defines how the web page information and presentation have been defined. While Webform is building our form components for rendering, we have the power now to inject extra presentation information for the convenience of our website visitors. We are welcome to add CSS classes to the HTML code in order to create the required presentation effect. The CSS styles for these additional classes may be added to our default theme CSS files.
There's more... Let us examine a few aspects of the markup component edit page in a little more detail.
Text format While in the edit mode for a markup component, we see a drop-down list under the Value textarea where we may select the format rules for our input code. More information on text format can be gleaned by clicking on the More information about text formats link on this page. Visiting http://drupal.org/node/213156 on the Drupal website is a good place for us to explore the value and implications of these options. 63
Discovering More Components
PHP code There is a PHP Filter module, which when enabled, allows administrators to insert PHP code into textareas on the site. This code will be executed while the corresponding page is being built. This feature is a potential security risk! We should not use this unless we absolutely have to. We should not give permission for this to anyone who is not a trusted user and who does not know both Drupal and PHP very well. A single typographical mistake in this PHP code can compromise the security and integrity of our entire website, as well as the underlying database. At best, mistakes here can result in the dreaded WSOD (White Screen Of Death) which indicates that our web server was unable to complete processing and render our web page. In the worst case, we could unintentionally reveal important security information regarding our site and installation details. It is far better, not to mention safer, to put together a standalone module to implement required functionality than to make use of the PHP code option. By default, the module is disabled as this feature is being phased out of Drupal altogether. This permission is initially only available to the main site administrator. Let's keep it that way— safety first! The security implications are definitely non-trivial.
Token values The markup component enjoys support for a wide range of token values, thus adding a dynamic complexion to the markup we enter here.
Conditional rules A new fieldset has become available to us on the component edit page. When we insert page breaks in our forms, Webform gives us the ability to specify rules that will determine whether a component is actually displayed on subsequent pages or not. The trigger fires based on the value of a component from one of the earlier pages in our form. We have the option to fire the trigger under one of two conditions: ff
The selected component contains a value included in the list under Values (that is, Is one of)
ff
The selected component contains a value not included in the list under Values (that is, Is not one of)
64
Chapter 4
For example, should we select the component Title and Is one of from the drop-down lists and enter Mr under Values, then this markup will display for all registering speakers who are your garden variety Mr. A registering user who selected a different title on the previous page, such as Dr, or Mrs, would not get to see this markup content at all.
This powerful feature permits us, to a large extent, to create dynamic forms based on user input. For example, by making all of the components on a particular subpage conditional based on the same component from a preceding subpage, Webform may skip showing that page altogether. All of the fields on such a page will be blank in the database.
Adding a hidden component This component is useful when we wish to have data stored in the database that the site visitor did not explicitly enter.
How to do it... Let's see how we can add an invisible component to our form. 1. Add a new Hidden component named Browser Type and click on the Add button.
65
Discovering More Components 2. Under Default value we enter the super token %server[HTTP_USER_AGENT] and click on Save component. 3. We leave CONDITIONAL RULES as they are to ensure that this component always receives a value.
How it works... Hidden fields are not truly hidden in the fullest sense of the word, they are merely hidden from view as far as the form user is concerned. The field is included in the generated HTML, but the web browser will simply not display the field on the web page. The super token that we entered (which only applies to visitors who are currently logged in on our site) will populate this field with information that can give us hints as to the operating system of the visitor's computer and which web browser they used to visit our site.
There's more... While hidden fields may be used for any purpose we require, the example we have worked through previously contains a caveat we should be aware of.
66
Chapter 4
Browser detection In the early days of the Internet, there was an ongoing battle for supremacy in terms of web browsers. Microsoft Internet Explorer and Netscape Navigator were two of the most popular browsers at the time, each with its own hardcore fan base. By making use of browser detection via the testing of the HTTP_USER_AGENT variable, proponents of the two sides would either limit, alter, or in extreme cases, even flatly deny content if we happened across their website with the wrong browser. Thankfully those days are behind us now and more cooperative spirit abounds. We should not be entirely surprised, however, to discover that many versions of Internet Explorer still masquerade themselves as being Mozilla browsers. As with the IP Address stored in submission metadata, we should not be over-reliant on this information as it is fairly easy to spoof. That being said, it is still common enough for some level of browser detection to occur, but this centers mainly around determining the ability of the browser to properly render the page content. There are web pages with content that cannot be normally displayed on Internet Explorer 6, for example, and web developers will use browser sniffing to determine the content that their applications should output. In Drupal, the bulk of this kind of thing normally gets handled in the CSS files.
Adding a grid component The grid component is quite commonly used in surveys, rather like the customer satisfaction survey cards used in many businesses, and the structure will be quite familiar to most of us. The general format is to have a list of questions down one side of a page or card, with space to score each question out of five.
How to do it... We're going to use a grid to survey our registering speakers and find out which aspects of their previous conference where the best and which aspects left them feeling that there was room for improvement. Conference organizers will then have sufficient information to focus their attentions properly when the results are collated on the Analysis page later and, hopefully, be able to wow everybody with their efficiency. 1. On our components overview page, we create a new grid component by entering the name Previous conference, selecting Grid from the component type list, checking the Mandatory box and clicking on Add.
67
Discovering More Components 2. To set up the scoring options for our users, we will enter the following into the Options textarea: 1|Poor 2|So-so 3|Okay 4|Rather good 5|Excellent
3. The questions against which our users will indicate their score options will be entered in the Questions textarea: Food|How was the food? Hotel|Was accommodation acceptable? Content|Were the workshops interesting? Organisation|Did everything run smoothly? Media|Were multi-media facilities adequate? Transport|Was adequate transportation available?
4. To help our registering speakers understand what we require from them, let's also enter some descriptive text in the Description textarea: Please rate these aspects of the last conference you attended (whether as a speaker or as a delegate).
5. Now we may save our grid component by clicking on Save component.
How it works... Webform will render our survey grid on the second page of our form. The scoring options are rendered as radio buttons so that only one option per question may be selected. As we have marked this component as being mandatory, each question becomes a required input and our speakers will need to answer all questions by selecting an appropriate scoring option. Both the questions and selectable options need to be specified with a safe key value as well as a human-readable value, separated by the vertical pipe character. This is similar to the manner in which we specify select options.
68
Chapter 4
There's more... When setting up our grid components we should take care to keep the option descriptions and questions as short as we can. Failure to do so may result in grids that appear squashed and are difficult for our users to read.
Display options A neat feature that the grid option has is the ability for us to randomize either the sequence of the options, the sequence of the questions, or both. If we cannot decide the exact order we want the questions to appear, we can just check a box and have them shuffled for each page view.
69
Discovering More Components
Grid analysis On the analysis page we will see our grid rendered as above, with the exception that the selectable option radio buttons have been replaced by a count of the number of times that each option has been selected. This gives us a nice snapshot view of the feedback gathered.
Adding a date component Obviously it would be handy if our Fictitious Conference organizers knew when our registering speakers would be arriving for the conference. Without this information they would not be able to ensure that suitable accommodation is available and so forth.
How to do it... Before we add the date component, let's add a fieldset called Arrival details to house the speaker's planned arrival date and time fields that we're about to create. 1. Enter the new component name as Arrival date and select Date from the component type list. As this is the required information, we check the Mandatory box before clicking on Add. 2. For the Default value we enter the value today. As we have chosen to use a relative date (that is, today, whenever that may be), it is recommended that we select Website timezone under Default value timezone. 3. Let's make it clear to registering speakers what we mean by arrival date by inserting the descriptive text: Let us know on which date will you arrive in the host city.
4. The remaining options may stay as they are and we click on Save component.
70
Chapter 4
5. On the form overview page, we can click our pointer on the drag-handle next to Arrival date and drag it slightly to the right so that this component will render within the Arrival details fieldset. 6. We must remember to click on Save to have the repositioning take effect!
How it works... Every time a new visitor comes to our form they will find that the current date is pre-populated into this date component. This is because we chose today's date as our default value. This could also have been left blank or set to a specific date in the future, or even the past. It is up to us to decide on something sensible to put in here.
There's more... We may find that it is sometimes easier to supply a list of of date options in the form of a select component as opposed to making use of the date component. This is especially true when we have a limited range of non-contiguous (that is, not in direct sequence) dates for our users to choose from, because we can then avoid issues around validation of the selected dates. That said, however, the date component offers a number of additional useful features.
Validating dates We also have the option of limiting input to a specific range of dates. This could mean that the input has to be after a certain date, before a certain date, or somewhere in between these two extremes.
Providing a pop-up calendar If we install and enable the Date Popup module, then we can make available to our form users a neat JavaScript pop-up calendar to ease the process of specifying the date. This is very useful from a user interface point of view as many people think better about dates when they can see a calendar. The Date Popup comes with the Date module which can be downloaded from its home page at http://drupal.org/project/date.
71
Discovering More Components
Handling date input formats PHP has a very powerful date and time function set. Thanks to this, we have great flexibility in how we specify date ranges and so on. We can learn more about the scope of what is possible by clicking on the GNU Date Input Format link that appears in various places on the Date component edit page. What we learn from that link applies to both Date and Time component types.
Adding a time component Adding a time component is every bit as easy, and powerful, as a date component.
How to do it... Let's add a component enabling our form users to submit a time. 1. Add a new component name Arrival time, select Time from the component type list, mark it as Mandatory and click on Add. 2. We enter now as the Default value for our time component and select Website timezone under Default value timezone. 3. Let's click on Save component and also add this component to the Arrival details fieldset, just as we did with the date component.
How it works... Time components render with two selection lists, one for hour and one for minute, to enable our form users to specify a particular time.
72
Chapter 4
There's more... On the time component edit page, we can optionally specify whether the time should be expressed in the form of a twelve-hour clock (that is, using A.M. and P.M., for example, 8:55 P.M.) or in the form of a twenty-four hour clock (for example, 20:55).
Adding a file component The last thing we need our example Webform to handle is giving our registering speakers facility to upload their speaker profile. Typically, this is a file created by word-processing software and contains a picture of the speaker along with a brief biography.
How to do it... 1. We will add a new File type component with the name Speaker profile and click on the Add button. 2. In the Description textarea on the component edit page, we enter these guidelines:
You may optionally upload your speaker profile here. File size is limited to 200KB and we accept most word processing software document types.
3. In the Validation fieldset, we can select which file types (as denoted by their file extensions) we wish to permit for upload. The first group of file extensions are selected by default. As these pertain to files in the category of Web Images we will want to de-select these by clicking on (select) next to Web Images. 4. We click on (select) next to the Documents category and see that all the file extensions for that category are selected. 5. Just underneath the file category selections we specify 200 as the Max Upload Size for files.
73
Discovering More Components 6. Let's also tidy up the way the component displays by changing the display Width to 40. Now we may click on Save component to finish.
How it works... In order to include a file in their form submissions, our users need to click on the Browse button. The web browser will open a file upload window which allows the user to browse the storage devices on their computer to locate the file they wish to upload. Assuming no validation error occurs, the file will be uploaded to the directory specified on the file component edit page. Here we may specify separate directories for different file components to help keep ourselves organized. Administrators will find a link to the uploaded files in the Results - Table listing.
There's more... Before we permit our users to upload files via our forms, we should ensure that our web server can handle the anticipated traffic and storage requirements. Many website hosting plans have specific restrictions as to how many bytes may be uploaded to the site, downloaded from the site, or stored on the site domain server. In some cases, we will find that the only consequence is an increased bill from the hosts, but we may find that our users will be unable to upload files at all.
File types We need not accept the full list of permitted extensions under any of the file categories. It is easy enough to only check the boxes for only those file types we wish to allow, even if they fall under different categories. 74
Chapter 4
It is helpful for our form users to explain in the Description textarea what limitations we are placing on the uploads as we did in the preceding example, otherwise they are left in the dark as to what is permissible and what is not. We do not want frustrated and unhappy users, so it is best we do what we can to keep them informed.
File gotcha We will find, with experience, that it pays to design our forms so that file upload components are on the last page of a form with no other validation components present on that page. After a user has selected the file they wish to upload and submit the form, any validation error will cause the uploaded file to be deleted by Drupal because it forms part of a rejected form submission. The user will need to correct the field that failed validation and reupload the file before submitting the form again. Sadly, many users will not notice that the upload needs to be redone and will complain bitterly that our web application has lost their file and is, therefore, broken. It is easier to set the form up in such a way that this sorry cycle cannot occur than it is to patiently explain to irate users why their form submission was incomplete.
Enhancing component descriptions with HTML Component descriptions can appear to be a little bland and lifeless as they seem to permit only plain text. Webform does, however, permit some HTML tagged input in these description textareas, that is, , <em>, <strong>, , and . The list of permitted HTML tags may be extended if we wish. Care must be taken lest we inadvertently open security holes, such as by permitting the <javascript> tags for example.
How to do it... To extend this list of permitted HTML we need to edit our site's settings.php file, ordinarily found in our installation's sites/default directory. 1. To add the line breaking
tag as a permitted tag, we need to override the defaults. This is achieved by opening our settings.php file with a text editor (we may need to change the file permissions to make it editable) and add the following line of code to the end of the file: $conf['webform_allowed_tags'] = array('a', 'em', 'strong', 'code', 'img', 'br');
75
Discovering More Components 2. Notice that we include the original defaults in the list. Failure to do so will mean that these tags cease to be permitted. The permitted tag names are listed in an array and the angle brackets are excluded. 3. Close the edited file and, if required, change the file permissions back to being uneditable. We are now able to add HTML line breaks in our component descriptions.
How it works... Most security patches for CMS have to do with problems caused by inadequate user input filtering. In Drupal, contributed modules bear the burden of filtering user input that bypasses the core systems, filtering processes. The filtering process itself operates in a simple manner. We configure permitted tags, that is, tags that are allowed to influence processing and rendering, and all other tags are summarily stripped out prior to output. The disallowed tags will be stored in the database, they are just not permitted to influence anything.
76
5
Tweaking the Form Settings In this chapter, we will cover: ff
Confirming submissions
ff
Limiting submissions
ff
Closing and reopening forms
ff
Limiting access to forms
ff
Displaying Webform as block
ff
Saving draft submissions
ff
Warning about previous submissions
ff
Customizing submit button text
Introduction Thanks to the power and convenience offered by the Webform components, we are able to create our forms in a fairly short space of time. Once we have all the necessary input fields in place, however, we discover that polishing the final product can take at least as long to accomplish. As we work through the additional form settings in this chapter we will, unavoidably, be creating additional factors to take into account during the testing phase of our forms as discussed at the end of Chapter 2, Trying Out Webform, and we should take care to ensure that everything works as expected.
Tweaking the Form Settings As we saw in Chapter 2, Trying Out Webform, and Chapter 4, Discovering More Components, there are several tweaks we can apply to the components themselves, such as hiding a field label or changing the display width of a text field for example. This first level of tweaking will probably require two or three iterations before all the stakeholders are happy to sign off on the way that the fields on our form render to the end user. Having done what we can to ensure that our form fields are logically grouped and well presented, we can now turn our attention to other details that will enhance both the user experience of our forms and our ability to manage what occurs on our forms. The Form settings page shows several options affecting the way our completed forms behave.
The remainder of this chapter assumes that we are logged in to our website as a user with full administration access to Webforms and have clicked on the Form settings sub-tab of our form's Webform tab.
Confirming submissions The best way to avoid uncertainty in users of our form is to give them explicit feedback that we have successfully received and processed their submitted data. By default, Webform displays a simple thank you message when a completed submission has been received. This message is displayed on a new page and contains a link to allow our users to return to a new blank form.
78
Chapter 5
However, we will often be required to give a more verbose confirmation message. This is also an excellent opportunity to supply additional information to our form users, or we could merely let them know that an e-mail is en route to them confirming their submission.
How to do it... Let's customize the confirmation message. Expand the SUBMISSION SETTINGS fieldset by clicking on the header. Enter the following text in the textarea entitled Confirmation message and click on the Save configuration button at the bottom of the page: Thank you for registering! An email confirming your registration has been sent to the supplied email address. We look forward to hosting you should the content committee accept your proposed presentation. Further information regarding the success of your proposal will follow in a few days. The Fictitious Conference Organizing Team.
79
Tweaking the Form Settings
How it works... When we previously submitted information via our form, we saw the default Webform confirmation message. By entering text into the Confirmation message textarea we effectively override the default text with our specified text. As with the default message, this text will display on a new page after we submit data to our form.
There's more... Webform is utilized in many different ways, so we may not always wish for the confirmation message to be displayed the same way. Let's look at some alternatives.
Displaying the confirmation as a Drupal message instead The default method for displaying the confirmation message is seen under the heading Redirection location on our Form settings page, where the Confirmation page option is preselected. This causes the confirmation message to be displayed on a separate web page as we saw previously. If we select the No redirect (reload current page) option then Webform will not redirect our users to a confirmation page, but will rather redisplay the Webform with the confirmation message above the form body as a Drupal system message.
80
Chapter 5
Displaying a custom confirmation page We also have the option of redirecting our users to a specially created piece of content that will act as our confirmation page outside the scope of Webform. Such a page would be created by adding new content and making a note of its URL. This URL is entered in the text field adjacent to the Custom URL option on the Form settings page and would take the standard form of node/xx, or whatever URL alias we may have specified for that page. When necessary, we may even redirect our users to a different website altogether by entering a fullyqualified URL (for example, http://www.example.com/confirmation.php). One of the benefits of using redirects for confirmations is that we may send submitted form values as arguments in the URL and thus include these dynamic values in the content of the custom page. With the aid of a token filter module, or even a custom module of our own, we are able to directly express submitted form values in the confirmation page content.
81
Tweaking the Form Settings
Why no Webform token replacements? Intuitively, we may be surprised that Webform token replacements are not available for use on the confirmation page. After all, we are telling the form users that their submission has been accepted, so why can we not directly display information that they have just recently entered? Well, the issue goes around data security. If we take a look at our browser address bar after completing and submitting a form, we notice that the Webform confirmation page URL contains the numeric submission identifier. This identifier, called sid, is used to locate the data pertaining to each submission and would be used to effect the token replacements. Assuming we have a mischievous and observant user who alters sid in the URL, how could Webform, with 100 percent certainty, prevent this user from seeing someone else's information? Without radical changes to the internal plumbing of Webform, there is currently no way to prevent this kind of potential abuse, hence the confirmation message text remains static.
Limiting submissions In certain situations, such as when conducting surveys or accepting competition entries, for example, we may wish to limit the number of submissions that a form user may make. Webform offers some methods for preventing folk from putting through multiple submissions, but it must be said that these methods cannot be guaranteed to be bullet-proof for anonymous users.
How to do it... Under the heading Submission limit on the Form settings page, we specify that our users are limited to making only one submission by entering Limit to 1 submission(s) ever. In this way we can prevent users of our Speaker Registration form from submitting more than one entry.
82
Chapter 5
How it works... In the case of registered and logged-in site users, Webform can easily determine whether or not a submission for this user has already been received. If we have received a previous submission, then the user will not be granted access to the form. In the case of anonymous users, Webform attempts to find previous submissions based on the user's IP address and presence of a web browser cookie.
There's more... As we have seen previously, we may limit the number of submissions made by a particular user. There are also several other limiting options that we could implement.
Limiting the frequency of submissions In cases where users may submit a form multiple times, but we need to limit how often they may make submissions, Webform allows us to alternatively specify how many submissions may be made on an hourly, daily, or weekly basis by any given user. This functionality enforces how often a particular user may enter a submission.
Limiting the total number of submissions We may also limit the total number of submissions that are made to a Webform. If we were selling ticket bookings via a Webform, for example, we would like for the form to automatically close when the prescribed number of bookings has been reached. Alternatively, we could limit the number of submissions that the form would accept every hour, every day, or every week.
Anonymous users caveat The IP address of our form users, on its own, cannot be considered to uniquely identify whether an anonymous site visitor has previously submitted a form. Many organizations have configured their outgoing Internet access in such a way that all users on the internal network appear to come from a single IP address. Adding to the uncertainty, many web browsers can be set to delete cookies when a browsing session has ended. It therefore becomes possible that a particular site visitor can circumvent the attempt to limit their multiple submissions by merely closing and re-opening their browser window.
83
Tweaking the Form Settings
Closing and reopening forms It may come to pass that our form is so inundated with submissions that the user responsible for administering the data requests us to close the form for a time. All the administrative functions will be available to suitably authorized administrators, but site visitors will not be able to make any new submissions. This will allow our administrators the time to adequately deal with the submissions they have before we reopen the floodgates.
How to do it... Under the heading of Status of this form on the Form settings page, we select the Closed option. When the time comes to reopen the form to traffic, we merely select the Open option to enable new submissions to be accepted.
How it works... This function is no more than an on-off switch. When the form is set to Closed, the node is still available to visitors and will still exist in our site menus, but none of the input fields will be available. Visitors will be shown a message stating that the form is currently closed for submissions.
84
Chapter 5
There's more... In the previous recipe, we learned that Webform can be set up to close forms automatically based on one or more criteria. Here we have seen that we may also manually close a form to submissions.
Closed, but still accessible As we can see, using this option to set the form as Closed does not prevent anyone from reaching the form at its URL. It merely prevents anyone from actually submitting data via the form. To make the form node completely inaccessible we would need to implement an access control solution (such as the Taxonomy Access or Node Privacy by Role modules), or even unset the published status of the node entirely.
Limiting access to forms Thanks to Webform's integration with the Drupal user management system, we can quite easily limit form access to particular user roles. Bearing in mind that any one user may belong to one or more roles, we can readily see that it is possible to set up fine-grained access rules for our forms.
Getting ready A standard Drupal installation comes with two default roles, one for anonymous users (that is, users who are not logged in) and another for authenticated users (that is, registered users who are currently logged in). Authenticated users may be assigned to one or more roles. We may proceed to People | Permissions | Roles to create a new role.
85
Tweaking the Form Settings Now, when we go into Edit on any user we see the various role titles accompanied by checkboxes which enable us to add or remove users from various roles.
How to do it... Under the heading Roles that can submit this webform on the Form settings page, we find a list of the roles that have been created for our site. To disable anonymous submissions for our form, we uncheck the box at the anonymous user role and click on the Save configuration button.
86
Chapter 5
Let's log out of the site and try to access our form to test this.
Once again we see that we are able to access the node, but we are not able to make a submission as an anonymous user.
How it works... Since we have denied access to anonymous users, only logged-in users will be able to complete a submission. The same principle would apply to any other role we disallowed. That is to say that users belonging to a role we have disallowed will not be able to make submissions. This is a great way to ensure that only specific user types are able to make submissions on our various forms.
Displaying Webform as block Drupal has a type of content called a block. Blocks are typically displayed in one of the sidebars of a site, although it is possible to place them in most regions of our theme.
87
Tweaking the Form Settings In a very general sense, blocks are chunks of discreet content that are meaningful in their own right, but separate from the main content of a particular page. A familiar example of a block is where we log in to our website.
Drupal blocks are highly configurable entities, to the extent that we may specify on which pages a block should show, or the sequence in which multiple blocks are displayed in a particular theme region. We can discover more about blocks in the Drupal documentation at http://drupal.org/documentation/modules/block.
How to do it... On the Webform Form settings page, we have the option to make our form available as block content. 1. Let us check the option Available as block under ADVANCED SETTINGS and then click on the Save configuration button. 2. Now let us click on Structure in our menu bar and click on Blocks. Scrolling down towards the bottom of the page we find our Webform listed among the disabled blocks. 3. Our form is available as a block, but is considered to be disabled because we have not yet assigned it to a region. 4. Let us click on the configure link that appears next to our form's name so that we can activate it as block content for our site. 5. Enter the text Webform as Block into the text field under Block title and then select the Form only option under Display mode. 6. Let's now select Sidebar first under our site's default theme and then click on the Save block button at the bottom of the page.
88
Chapter 5
7. When we now click on the Home icon in the menu bar, we will see that our Webform appears in the right-hand sidebar of our site (although it is spilling over into the main content area).
How it works... The Webform module makes it possible to render our forms as either traditional Drupal nodes or as blocks. If we were making a custom Contact Us form, for example, that has only three or four fields, it seems wasteful to have this tiny form occupy an entire page. Such forms are possibly best placed in a block where they can be accessed directly from almost anywhere on our site because, as blocks, they are independent of the node content area of our site. It is recommended to use a fluid width theme when displaying our forms as blocks in sidebars. Fixed width themes can have difficulty displaying forms neatly in sidebars (as we saw previously). However, this can be overcome by tweaking input field widths and so on.
There's more... We have a few options that affect how our form will display and behave when we use it as a block.
89
Tweaking the Form Settings
Display mode When we initially created our Webform we filled out a Body field. The text we entered here displays above the actual form portion of our Webform, that is, above that part of the page where our fields start being rendered. When we opt to display our form as a block we have three display options to choose from in our block configuration: ff
Form only: Displays only the form input fields portion of the Webform.
ff
Full node: Displays the Body text as well as the input fields portion of the Webform.
ff
Teaser: Displays only the Body text or a shortened version of it (depending on site settings). This option introduces a Read more link which would redirect our users to the Webform node itself.
Which of these we choose to implement would depend very much on our reasons for having the form available as a block. For a miniature contact form it would probably serve us to display the form only, whereas a more complicated form should probably use the teaser option to attract interested parties to our form proper.
90
Chapter 5
Show all Webform pages in block This option only applies to multipage forms. Webform offers us the choice of having all of the different pages of our multipage form display within the block or only the first page. If we leave this option unchecked then our form users will be redirected to the Webform node when they click on the Next page button. They would fill out the fields on page one and be redirected to the full node displaying page two. When we check this option, the main content area of our site will not change as our users progress through our various form pages.
Block form error messages It seems somewhat counter-intuitive that Webform error messages arising from forms displayed as blocks should display above the main page content. On the face of it, we would expect these error messages to appear in our Webform block. The reason for these messages appearing above the main page content is very simple: like all good modules, Webform uses the core Drupal error messaging system. Most themes are set up to render Drupal error messages at the top of the main content area. The unexpected behavior is theme driven, not an inadequacy in Webform.
Saving draft submissions A convenience we may offer to the logged-in registered users of our site is the ability to store incomplete multipage forms, that is, drafts. What this means is that a user can take days to complete a form submission, across multiple visits to our site, without losing the information they previously submitted.
How to do it... Under the ADVANCED SETTINGS heading on our Form Settings page, check the box at Show "Save draft" button.
91
Tweaking the Form Settings When we view our form now we will see that a Save Draft button has appeared next to our Next Page button.
How it works... Since Webform can identify a logged-in user and match that specific user to a specific submission, there is no difficulty attached to permitting such a user to save a partial submission. There is no real benefit to allowing a user to save an incomplete single page form, so this option is only applicable where our Webform has one or more page breaks. At any stage during the process of filling out our form, our logged-in users may now click the Save draft button and have Webform store their incomplete submission. Webform will display a message explaining that the draft has been saved and that submitted values will be prepopulated into the form when they return.
92
Chapter 5
We may test this functionality by completing one or two fields in our example Webform, saving it as draft, navigating to another page, and then returning to our Webform.
There's more... Webform also offers the facility to automatically save draft submissions even though the user has not specifically asked for it.
Automatically save as draft between pages This world abounds with distractions. It is not uncommon for a user to commence filling out a form, suffer a distraction, or even a power failure, that prevents them completing their submission, and then have to redo everything at a later point in time. When we check the Automatically save as draft between pages option under the ADVANCED SETTINGS, Webform will save the logged-in user's data as they progress through the various pages of our form. Should they be unable to complete the form at the first attempt, for whatever reason, their previously submitted information will be available when they later return to the form. The data will remain in draft status until such time as the user clicks on Submit on the last page of our multipage form. Note that the Save draft button will only appear on our form when we have selected the Show "Save draft" button option. When we select only the Automatically save as draft between pages option, the Save draft button will not be visible. However, the data submitted on each page will still be stored in draft status.
Warning about previous submissions Logged-in users who have already completed a form submission and later return to that form will, by default, be warned that they have already completed the form. The warning also contains a link which, when clicked, will show the user a listing of the previous submissions they have already completed. This facility may be disabled when we have no concern around receiving multiple submissions from our logged-in users.
93
Tweaking the Form Settings
How to do it... Uncheck the box at the Show the notification about previous submissions option under ADVANCED SETTINGS on the Form settings page.
How it works... Webform is configured to enable this option by default. By disabling the option, we remove the warning message that displays when a logged-in user revisits a Webform they have already completed.
Customizing submit button text The Submit button is universally understood as it appears on the majority of forms on the Internet. However, there are times when it would be nice to make the text a little more explanatory.
94
Chapter 5
How to do it... The ADVANCED SETTINGS section of the Form settings page contains a text field under the heading Submit button text. Let's type the text Click here to submit your registration into the text field and save our configuration change. View the form to see the change to our button.
How it works... There is nothing very fancy about this functionality as all it does is substitute the default submit button label with whatever we type into the appropriate text field.
95
6
Extending Webform In this chapter, we will cover the following topics: ff
Enabling the Select (or other) module
ff
Using the Options Element
ff
Defining custom option lists
ff
Enabling date pop-up
ff
Sending HTML e-mails
ff
Preventing spam with CAPTCHA
ff
Advanced data validation
Introduction As we build our Webforms we may occasionally identify a need for additional functionality that is not available in Webform. Thankfully, in the vibrant Drupal community, there is often already a solution available in one form or another. Just as the Drupal core can be extended by contributed modules (such as Webform), so too can Webform be extended by contributed modules. In other cases, the Webform maintainers can change programming code to leverage functionality that is made possible by other contributed modules. In this chapter, we will discover some modules with which we may embellish our Webforms and their functionality. The modules we will cover here do not form a definitive list of what is available, nor is there any negative reflection on modules not described in this chapter. As with any book, there are space constraints that unfortunately enforce a certain amount of pruning.
Extending Webform We should also note that most of the modules we will touch on are broad enough in scope to warrant books all of their own. We will be directing our attention only to those minimal aspects of the modules as are required for our demonstration purposes. Nothing prevents us from further research and experimentation than is described as follows and, usually, the various project home pages will be an excellent place to start. While the contributed modules described here are all useful in their own right, we should refrain from installing modules that we do not really need, or will not fully utilize. The main reason for this caution is that our site slows down with many modules enabled, because there is more processing being handled by the server. Secondly, the occasional security breaches on Drupal websites come about through one or two inadvertent loopholes created by contributed modules. By limiting ourselves to only those modules that actually contribute to our overall website design and scope, we automatically reduce the chances of a breach, as well as benefiting from a faster loading site. The methodology for downloading and installing modules was described in Chapter 1, Setting up Webform, under the heading Downloading and Installing Webform. In the following sections it is assumed that the process of installing each module has been successfully completed and that the module has been enabled on the Modules administrative page by checking the required boxes and clicking on the Save configuration button.
Enabling the Select (or other) module We may find that the standard select options on our forms cannot satisfactorily handle all situations. For instance, on our example Speaker Registration form we have an honorific title select list which covers all the basics (Mr, Mrs, Ms, and so on.). This list does not adequately provide for persons who require additional options, such as those in the military who need to be addressed by their rank, for example Sgt, Lt, or Capt. The Select (or other) module enables our form users to enter their required title when it does not appear on our list of options.
Getting ready Let's proceed to the project home page to download, install, and enable the module: http://drupal.org/project/select_or_other.
98
Chapter 6
How to do it... On our Title component edit page we now have two new configuration options. 1. Let's enable the Allow "Other..." option functionality and update the text as per the following screenshot:
2. Make the configuration changes effective by clicking on the Save component button.
How it works... Let's view our Webform to see the functionality in action. When we click on the title selection list we see that our list has an extra option reflecting the text we specified on our component edit page. As we select the Other (please specify below) option, a new text field appears for us to enter a title that does not appear in the existing list.
There's more... This functionality is now available to any select components on our Webforms, including checkbox lists and radio button lists.
99
Extending Webform
Analyzing submissions Not only has our form functionality been updated, but so has the submissions analysis page. A count of any Other (please specify below) options that have been entered will display on the standard analysis page. When we click on the view link next to the count we will see a breakdown of the new options that have been entered.
Using the Options Element Not all contributed modules are about making life better for just our website users. Some exist to improve the lives of website administrators too. As we saw in Chapter 2, Trying Out Webform, the standard method is to type our selection list options into a textarea with an internal key and screen text value, separated by a vertical pipe symbol. The Options Element module provides Webform with a neat user interface for setting up the select options we wish to use on our forms.
Getting ready Let us go to the project home page to download, install, and enable the module: http://drupal.org/project/options_element.
How to do it... Returning to our Title component edit page, we find that the somewhat dreary plaintext area where we entered our select options previously has been replaced by a handy tabular interface that operates a little more intuitively for many administrators.
100
Chapter 6
How it works... We can now easily change the sequence of our options by clicking on and dragging the handles to the left of each option row. Setting a default selection is achieved by checking the Default radio button on the pertinent row. An option may be deleted by clicking on the red cross and a new option can be inserted below the current option by clicking on the green plus sign. Should we wish to return to the standard way of doing things all we need do is click on the Manual entry link below the OPTIONS table.
There's more... Let's take a look at how the Options element operates under the hood.
Custom option keys By default, the internal option key used by Webform will be a numeric value, counting from zero upward. In our case here, the option keys are the same as we originally entered.
101
Extending Webform For those occasions where we would rather specify a different key value we can check the Customize keys (Advanced) option. Each option row in the table now expands to include space where we may specify the option keys ourselves.
Defining custom option lists Webform enables developers to create predefined lists that can be used to populate select lists. Instead of applying a copy-and-paste methodology for frequently used lists on a website, we can create an extension module that makes such option lists available to all Webform select components. Apart from the time saving this represents to administrators creating Webforms, we will only need to make changes in one place to affect all Webform components making use of a custom list. This is a developer activity and the following task description assumes some knowledge of PHP and Drupal programming.
Getting ready Let's get the ball rolling by creating a folder to house our extension module. In the sites/all/modules folder of our website, we create a new subfolder called webform_custom_lists.
102
Chapter 6
How to do it... Drupal modules require a minimum of two files in their module folders: an info file that declares the module to the Drupal system and a module file that does the actual work. 1. First we will save the following code in a file called webform_custom_lists.info in our newly created sites/all/modules/webform_custom_lists folder: name = Webform Custom Lists description = Custom option lists for Webform select components. core = 7.x package = Webform dependencies[] = webform
2. This file introduces our module to the Drupal system. 3. To have Webform generate the custom list we will save the following code in a file called webform_custom_lists.module in our sites/all/modules/webform_ custom_lists folder: