Table of ContentsPreface 1 Introduction 5Downloading and installing Webform 6Configuring Webform for our website 8Setting user roles and permissions 12 Introduction 15 Adding textfield c
Trang 2Drupal 7 Webform Cookbook
Over 70 recipes for exploiting one of Drupal's more popular contributed modules
Vernon Denny
Trang 3Drupal 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
Trang 4Project Coordinator Sai Gamare
Proofreader Bernadette Watkins
Indexer Hemangini Bari
Production Coordinator Alwin Roy
Cover Work Alwin Roy
Trang 5About 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
leading-edge 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!
Trang 6About 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
Trang 7profile 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
Trang 8of 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
Trang 9to 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
Trang 10Support 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 service@packtpub.com 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?
f Fully searchable across every book published by Packt
f Copy and paste, print and bookmark content
f 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
Trang 12be a big day
Trang 14Table of Contents
Preface 1
Introduction 5Downloading and installing Webform 6Configuring Webform for our website 8Setting user roles and permissions 12
Introduction 15
Adding textfield components to our Webform 19
Adding textarea components 26Adding fieldset components 27
Configuring a reply e-mail 33
Introduction 37Viewing submissions metadata 38
Trang 15Chapter 4: Discovering More Components 59
Adding a page break component 60
Enhancing component descriptions with HTML 75
Introduction 77
Closing and reopening forms 84
Displaying Webform as block 87
Warning about previous submissions 93Customizing submit button text 94
Enabling the Select (or other) module 98Using the Options Element 100Defining custom option lists 102
Preventing spam with CAPTCHA 111
Preparing our custom theme 120
Theming the confirmation page 131Theming Webform e-mail headers 134
Introduction 137
Trang 16Chapter 9: Creating Webform Components 159
Creating the component module 162Defining component features 163Defining component defaults 167
Displaying and reporting component data 173
Validating submitted data 178
Creating a new select component 191
Creating a conditional action 195
Confirming the requested action 199
Counting Webform submissions with views 216Tracking changes to submissions 226
Defining same-page conditional fields 234Validating on the client side 239
Trang 18Consistently 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
Trang 19Chapter 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
Trang 20package = 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 feedback@packtpub.com, and mention the book title via the subject of your message
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com
If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, 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
Trang 21Downloading 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 copyright@packtpub.com with a link to the suspected
Trang 22Setting up Webform
In this chapter, we will cover the following:
f Downloading and installing Webform
f Configuring Webform for our website
f 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
Trang 23Apart 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)
Trang 24This 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.
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
Trang 258 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
Trang 26How 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
Trang 27Each 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:
Trang 28Advanced 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
Trang 29Setting 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
Trang 30Reading 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
Trang 31Looking 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
Trang 32Trying Out Webform
In this chapter, we will cover:
f Creating a Webform node
f Adding textfield components to our Webform
f Cloning components
f Adding e-mail components
f Adding textarea components
f Adding fieldset components
f Adding select components
f Configuring a reply e-mail
f 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
Trang 33It 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
Trang 34Creating 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
Trang 355 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
Trang 36Adding 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
Trang 37Getting 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:
Trang 38Our 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
Trang 39Should 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
Trang 40The 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:
f 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
f 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
f Maxlength: Here we can specify the maximum number of characters that users may enter into a field
f 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
f 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
f 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