Tải bản đầy đủ (.pdf) (274 trang)

Drupal 7 webform cookbook

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.6 MB, 274 trang )

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 ()
Credits
Author


Vernon Denny
Reviewers
Richard Carter
Richard Eriksson
John K. Murphy
Jeff Smith
Ravishankar Somasundaram
Acquisition Editor
Usha Iyer
Lead Technical Editor
Dayan Hyames
Technical Editors
Manasi Poonthottam
Ankita Shashi
Project Coordinator
Sai Gamare
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 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!
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 (), 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,
Denitive Guide to Drupal 7, and Drupal 7 Business Solutions, and is a co-founder of the
Drupal North East user group ().
He blogs at and tweets nonsense at
/>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
prole at Richard has worked on the community
support and systems administration team at Bryght, the rst 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 ( />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 nal 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 eld 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 ofcial
third-party developer of Moodle code, Ravi shares his knowledge by helping people on the
Moodle ofcial 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 rms 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 articial 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 les, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support les and downloads related to
your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
les 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
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.

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

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
Conguring Webform for our website 8
Setting user roles and permissions 12
Chapter 2: Trying Out Webform 15
Introduction 15
Creating a Webform node 17
Adding texteld components to our Webform 19
Cloning components 24
Adding e-mail components 25
Adding textarea components 26
Adding eldset components 27
Adding select components 31
Conguring a reply e-mail 33
Testing our Webform 34
Chapter 3: Working with Submissions 37
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
ii
Table of Contents
Chapter 4: Discovering More Components 59
Introduction 59
Adding a page break component 60
Adding a markup component 62
Adding a hidden component 65
Adding a grid component 67
Adding a date component 70
Adding a time component 72
Adding a le component 73
Enhancing component descriptions with HTML 75
Chapter 5: Tweaking the Form Settings 77
Introduction 77
Conrming 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
Chapter 6: Extending Webform 97
Introduction 97
Enabling the Select (or other) module 98
Using the Options Element 100

Dening custom option lists 102
Enabling date pop-up 105
Sending HTML e-mails 107
Preventing spam with CAPTCHA 111
Advanced data validation 114
Chapter 7: Theming Webform 119
Introduction 119
Preparing our custom theme 120
Adding custom CSS 123
Adding JavaScript tricks 127
Theming the conrmation page 131
Theming Webform e-mail headers 134
Chapter 8: Acting on Webform Submissions 137
Introduction 137
Modifying submitted data 138
Adding custom validation 146
iii
Table of Contents
Chapter 9: Creating Webform Components 159
Introduction 159
Creating the component module 162
Dening component features 163
Dening component defaults 167
Editing components 168
Rendering components 171
Displaying and reporting component data 173
Analyzing component data 176
Validating submitted data 178
Testing the module 181
Chapter 10: Creating Submission Actions 189

Introduction 189
Creating a new select component 191
Creating the module 194
Creating a conditional action 195
Adding a menu item 197
Conrming the requested action 199
Updating a submission 200
Sending an e-mail 202
Testing the module 205
Chapter 11: Presenting and Managing Data 209
Introduction 209
Building custom reports 210
Counting Webform submissions with views 216
Tracking changes to submissions 226
Chapter 12: Going Out of the Box 229
Introduction 229
Building a survey form 230
Dening same-page conditional elds 234
Validating on the client side 239
Importing submissions 242
Index 249

Preface
Consistently ranked in the top 15 of the most installed Drupal contributed modules (see
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 conguration options.
Chapter 2, Trying Out Webform, introduces Webform components, building, and testing our
rst 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
2
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 elds 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 nd 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
Preface
3
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 , 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
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.
Preface
4
Downloading the example code
You can download the example code les for all Packt books you have purchased from your
account at . If you purchased this book elsewhere, you can
visit and register to have the les e-mailed
directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you nd 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 nd any errata, please report them
by visiting selecting your book, clicking on the errata
submission form link, and entering the details of your errata. Once your errata are veried, 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 />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 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 if you are having a problem with any
aspect of the book, and we will do our best to address it.
1
Setting up Webform
In this chapter, we will cover the following:
f Downloading and installing Webform
f Conguring 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.
Setting up Webform
6
Apart from supporting all the standard HTML form input elements, such as textelds, radio
buttons, and selection lists, Webform also offers some custom components, such as survey
grids and date or time elds. 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 elds (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 specic eld).
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
congure Webform to send an e-mail to the submitting user conrming receipt of their
submission, as well as sending a notication 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 specic Webform installation bigger and better.

When we cannot nd a module that offers the functionality we seek, we may extend Webform
by developing our own custom modules.
We will better understand the benets 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
conguration options before getting started with our rst 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 to obtain the latest version of
Drupal. A detailed installation guide for Drupal can be found at the />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).
Chapter 1
7
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 nd that the location of some tabs, links, and buttons vary between
the two versions. Screenshot images in the pages and chapters that follow will reect 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 rst digit (we're working on Drupal version 7).
3. Save the compressed le 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 le and
perhaps browse around the Webform system les and folders. We must be careful to
not inadvertently change the contents of any of the les 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 re up our favorite web browser, navigate to our home
page, and log in.
Setting up Webform
8
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 conguration 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
les. It really is just a case of plug it in and switch it on!

Conguring Webform for our website
Now that we have Webform installed and enabled, let's take a look at some of the global
conguration settings that will apply as defaults on every piece of Webform content that you
create on this site.
Webform provides a highly exible and congurable content type. Certain options have been
identied as being generally constant for all Webforms on a particular site and these have
been isolated on the Webform settings page.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×