Multiple Submit Buttons on a Webform

multiple-webform-submitI’ve spent a lot of time working with hook_form_alter() functions to modify forms, but the other day I was stumped by a simple problem. I needed to have two submit buttons on a form. By default, in the latest branch of Webform, you can change the text label on the default submit button for a webform. If you take a look at the screenshot on the right, you’ll see what my demo form looks like. The “Request More Information” button is the default submit button. The “Refer a Friend” button is the one I’m showing how to add via hook_form_alter().

Let’s talk about the reason for having a second submit button. The specification for the form showed two buttons. If the user clicks “Refer a Friend” the form will submit with an additional piece of information saying the user IS referring a friend. If the “Request More Information” button is clicked, the form will be submitted and the “referred by a friend” status will be “no.”

First, I created a hidden field called “Refer a Friend.” I setup a default value of “no” for this field. There aren’t any dependencies or logic built around this field, so I didn’t bother with 1 or 0, TRUE or FALSE. I want the confirmation email to either say “yes” or “no.”

Next, using hook_form_alter(), I injected an additional submit button. Here’s the code for that:

So, if you read through that little bit of code you’ll see my comment about the submit button’s #value property. In order for the form to be processed “normally” as it would if the default submit button was clicked, I had to make the buttons have the same value. I spent a great deal of time trying to solve this, and for the project I was doing it simply wasn’t worth spending more time investigating. I’m kind of embarrassed to say that, but those are the facts!

Now, if I view the form at this point I will have two seemingly-identical buttons. We’re going to use jQuery to re-label the new one. The entire site requires jQuery to run, so I am not concerned with this implementation. Am I losing developer street cred yet? haha.

As of right now, nothing special will happen if you click the “Refer a Friend” button. The form will be submitted as normal. So, let’s add a validation handler to set the value of the hidden “Refer a Friend” element.

Now all that is left is to change the text in the new button. Currently, it reads “Request More Info.” Using a little bit of jQuery, we can change this to “Refer a Friend.” This does not change the processing of the form. Webform ties a lot into which button is clicked, which is why the validation handler has some strange variable-checking in the conditional.

Well, this example is kind of pathetic, but it works great. If you have a better solution, please provide me with a link or description of the solution. There is undoubtedly an exclusively-php solution for the “two submit buttons do the same thing” problem.

Leave a Reply

Your email address will not be published.