Shane Stillwell
Shane Stillwell

Reputation: 3248

How do I detect which submit button was pressed on a Zend Framework form?

I have a Zend Framework form that has two submit buttons

$changes = new Zend_Form_Element_Submit('save_changes');
$changes->setLabel('Save Changes');

$delete = new Zend_Form_Element_Submit('delete');
$delete->setLabel('Delete');

Which renders HTML like such:

<input type="submit" name="save_changes" id="user_save_changes" value="Save Changes" >
<input type="submit" name="delete" id="user_delete" value="Delete" >

In the controller, how do I determine which button the user pressed?

Upvotes: 4

Views: 12565

Answers (5)

mahkill
mahkill

Reputation: 25

$data = $this->getRequest()->getPost();
if (array_key_exists('save_changes', $data)) {
..
} else if (array_key_exists('delete', $data)) {
..
}

Upvotes: 0

SuperNoob
SuperNoob

Reputation: 392

Actually you can get this by:

if($this->getRequest()->getPost('save_changes'){
//Code here
}

if($this->getRequest()->getPost('delete'){
//Code here
}

The reason I made two if condition because you can't do if else because one you load that page even though you didn't click any submit button, the other condition will be executed.

Example:

if($this->getRequest()->getPost('save_changes'){
  //once you load this will become true because you didn't click this
}else{
  //once you load this page this will become true because you didn't click the save_changes submit button
}

True story.

Upvotes: 5

Fernando Barrocal
Fernando Barrocal

Reputation: 13162

Since you are using Zend I would recommend a more Zend-ish approach.

You can call elements directly by theirs names and Zend has a method for form buttons (buttons, reset, submits) called isChecked().

in your code it would be:

if ($form->save_changes->isChecked()) {
    // Saving ...
else if ($form->delete->isChecked()) {
    // Removing ...

Upvotes: 8

mahesh
mahesh

Reputation: 1

 $formData = $this->getRequest()->getPost(); 

if($formData['submit']=='save_changes'){ // echo "save chanes" ; }
if($formData['submit']=='delete'){ // echo "delete";}

Upvotes: -1

Daff
Daff

Reputation: 44205

In your case you should just be able to check

if(isset($_POST['save_changes'])
// or
if(isset($_POST['delete'])

Since only the value of the clicked button will be submitted.

Usually you give both buttons the same name (e.g. action) and then set the value to the action you want to perform. Unfortunately that doesn't work very well with IE. Check this page for more information about different solutions for multiple submit buttons.

Upvotes: 10

Related Questions