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

南楼画角 提交于 2019-12-11 01:39:34

问题


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?


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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



回答5:


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

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


来源:https://stackoverflow.com/questions/5669052/how-do-i-detect-which-submit-button-was-pressed-on-a-zend-framework-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!