sebb
sebb

Reputation: 1

PHP: Handling Multiple Submit Buttons

Would like to get a consensus as to what the best practice is in this scenario:

Muliple submit buttons, is it better to handle this by having separate FORMS for each one of the submits, OR is it okay to have one form and check which button was pressed?

thank you for your input :D

Upvotes: 0

Views: 1084

Answers (4)

poeschlorn
poeschlorn

Reputation: 12440

In my case I would do that similar to Andrew Heath, but I woulg give the buttons a unique name. So the && clause is not needed

Upvotes: 2

Drew
Drew

Reputation: 6274

Assuming you're doing this solely in PHP, just change the values for each button and check for existence in POST:

if (isset($_POST['button1']) && $_POST['button1'] == "Previous") {

  // do something

} else if (isset($_POST['button1']) && $_POST['button1'] == "Next") {

  // do something else

} else {

  // nothing has been submitted, display default

}

Upvotes: 2

phsource
phsource

Reputation: 2446

Of course, it always depends on the purpose. However, as a rule-of-thumb, I do the natural thing:

  • If there are form fields that would be submitted by either submit button, use Javascript and detect the submit button pressed with a handler.
  • In all other cases, use different forms.

I try to avoid having merged forms (the first option) as:

  1. An input name change affects both of the submit target pages, and requires changes on both of the <form action="blah"> pages.
  2. Javascript is not always enabled on browsers

Upvotes: 0

Mitch Dempsey
Mitch Dempsey

Reputation: 39869

Well, depending on the content of the form, having 2 submit buttons would be the only way to achieve what you want. (How would you have 2 forms if there were text boxes.. replicating the entered data with javascript would be rather annoying)

I would stick with just checking to see which button was pushed, it should be much easier.

Upvotes: 0

Related Questions