Sie sind auf Seite 1von 27

Drupal 7 Webform Cookbook

Vernon Denny

Chapter No. 3 "Working with Submissions"

In this package, you will find:


A Biography of the author of the book A preview chapter from the book, Chapter NO.3 "Working with Submissions" A synopsis of the books content Information on where to buy this book

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.

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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!

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Drupal 7 Webform Cookbook


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 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 forms 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. 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.

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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.

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Working with Submissions


In this chapter, we will cover the following topics:

Viewing submissions metadata Viewing submissions Editing submissions Analyzing submitted data Downloading submissions Deleting submissions Clearing the database 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: CCreate new data to be stored RRead or retrieve data that has been stored previously UUpdate data that has been stored previously DDelete or destroy previously stored data that we no longer have use for

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Working with Submissions Apparently rst 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 rst 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 ll out the form elds 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 nd 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 rst need a method to locate the data that requires changing. This type of activity falls under the R of CRUDreading 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 desiredeither 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:

When the data was submitted The user who submitted the data Where the data was submitted from

38

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 nd 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 specic user's prole 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 trafc. 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 trafc from. Under the OPERATIONS column, we nd 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 rst 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Chapter 3

To rearrange the listing in ascending submission ID sequence, all we need do is click on the # column headingthe 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 nd 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 eld 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 Astonishmentmeaning, 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 eld sets are dened 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 specied direction.

Resending e-mails
There will come a time when we need to resend the automatic e-mails we congured 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 conrmation 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 conguration exercise in Chapter 2, Trying Out Webform, we may set up more than one e-mail in our form conguration. In the case where we have multiple e-mails congured, Webform gives us the ability to specify which e-mails we wish to resend.

42

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 specic 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 nal 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 elds 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 elds 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 congured validation rules, however. Required input elds 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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, nancial, 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 inefcient 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 strengthsits exibility. 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 elds 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 eld has its own column and each submission is stored as a single row of information (for the non-technically mindedsimilar to a spreadsheet layout), the reality is quite different.

45

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 y. Table columns would need to be added or removed dynamically. Join queries would need to be dynamically built and modied as the form conguration 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 elds, 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, nally, the actual data value. The storage strategy adopted by Webform is not so much the most efcient of all possible options as it is the least inefcient. The motivation is to retain as much exibility 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 elds, of which ten elds 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 ve 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 eld, 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 eld blank, how many have included a value for the component, and nally, 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Chapter 3

How to do it...
There are several options we may use to dene 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 le directly, or to rst save the le to our computer, before we open it with our spreadsheet application software. Let us select the option to open the le.

49

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Working with Submissions 3. While most spreadsheet applications can import data in a variety of formats, they do tend to expect the le to be in a special binary format. Webform exports data as a at text le, using special characters to separate columns (that is, elds), with each spreadsheet row on its own line. Our spreadsheet application will now ask us to conrm that it has correctly identied 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 Ofce 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Chapter 3

The rst 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 inuence the downloaded data le.

Export format
As the submitted data is exported in text le format, we need to tell Webform how our spreadsheet application knows where one eld's data ends and the next one starts. We achieve this through dening the limits of each cell by means of a specied 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 nd that our spreadsheet software will split one eld'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 dene a Select Options component, such as our Title eld from the form built in Chapter 2, Trying Out Webform, we specify two values per option on the component settings pagethe 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 elds are required, we may uncheck the elds we do not need.

51

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Working with Submissions Should we decide, for example, that we require a list containing only the registered speakers' rst 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 le, we would, intuitively, uncheck the box at Submission information.

Download range options


Just as we do not always require all elds to be included in a download, we may also wish to download only a specic 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 specied range.

Deleting submissions
The nal set of functionality required by the CRUD design pattern is the facility to delete (or destroy) data.

52

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 conrmation 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 efcient 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 conrmation screen where we can either conrm 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 rst 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

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 denitive 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 les 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 les. 2. Within this new folder we'll be creating two les for our custom module to be properly recognized by the Drupal system. 3. Using our favorite text editor, let us open a new empty le, enter the following code, and save the le 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 es 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 es e-mailed directly to you.

4. The info le 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 rst, because Drupal will not allow us to disable a module on which other modules depend.
55

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Working with Submissions 6. Now for the bit that does the actual work. Let's open a new empty le in our text editor and save the following code as a le named webform_custom.module.
<?php // Make changes to the Results menu sub-tabs. function webform_custom_menu_alter(&$items) { // Set Results Table sub-tab as new default sub-tab. $items['node/%webform_menu/webform-results']['page callback'] = 'webform_results_table'; $items['node/%webform_menu/webform-results']['page arguments'] = array(1, '50'); $items['node/%webform_menu/webform-results/table']['type'] = MENU_DEFAULT_LOCAL_TASK; $items['node/%webform_menu/webform-results/submissions']['type'] = MENU_LOCAL_TASK; // Rename Results Table sub-tab to Database. $items['node/%webform_menu/webform-results/table']['title'] = 'Database'; // Change the order of the sub-tabs. $items['node/%webform_menu/webform-results/table']['weight'] = 4; $items['node/%webform_menu/webform-results/download']['weight'] = 5; $items['node/%webform_menu/webform-results/analysis']['weight'] = 6; $items['node/%webform_menu/webform-results/submissions'] ['weight'] = 7; }

There is no closing ?> 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 rst 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 weighta lower weight oats towards the top and a heavier weight oats towards the bottom. In the last four lines, then, we are changing the display sequence of the sub-tabs on the Results page.
56

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Chapter 3

10. Just as we did when we installed the Webform module, we need to copy our module folder (with the two les 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 nd our module, check the box to enable it, and then click on the Save conguration button.

How it works...
The Drupal system scans through the /sites/all/modules folders looking for the .info les with corresponding .module les. 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

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Where to buy this book


You can buy Drupal 7 Webform Cookbook from the Packt Publishing website: http://www.packtpub.com/drupal-7-webform-popular-contributedmodules-cookbook/book.
Free shipping to the US, UK, Europe and selected Asian countries. For more information, please read our shipping policy.

Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and most internet book retailers.

www.PacktPub.com

For More Information: www.packtpub.com/drupal-7-webform-popular-contributed-modulescookbook/book

Das könnte Ihnen auch gefallen