In CakePHP 1.3 you can create a form with multiple submit buttons:
echo $this->Form->submit('Submit 1', array('name'=>'submit');
echo $this->Form->submit('Submit 2', array('name'=>'submit');
and detect which submit button was pressed in the controller with:
if (isset($this->params['form']['submit']) && $this->params['form']['submit'] == "Submit 1") {
// first button clicked
}
In CakePHP, $this->params['form'] isn't set and the clicked button value doesn't appear anywhere in $this->request, $this->request->data, $this->params, $this->data or $_POST.
How do I determine which button has been clicked in CakePHP 2.0?
Thanks in advance.
Edit:
As requested, here's the code for the form:
<?php echo $this->Form->create('History', array('action'=>'add')); ?>
<div class='submit'>
<?php
echo $this->Form->submit('Yes', array('div'=>false, 'name'=>'submit'));
echo $this->Form->submit('No', array('div'=>false, 'name'=>'submit'));
?>
</div>
<?php echo $this->Form->end()?>
And the output of the form:
<form action="/projects/kings_recruit/trunk/www/histories/add" id="HistoryAddForm" method="post" accept-charset="utf-8">
<div style="display:none;">
<input name="_method" value="POST" type="hidden">
</div>
<div class="submit">
<input name="submit" value="Yes" type="submit">
<input name="submit" value="No" type="submit">
</div>
</form>
Don't use the same name for both submit buttons. Consider this example:
debug($this->request->data) will produce the following when the "Yes" button is clicked:
And here it is when the "No" button is clicked:
To check which button was clicked:
Generally it is a bad practise to use the same name for both submit buttons. There should be a "submit" key in the $_POST and $this->request->data
I tested this in CakePHP 2.1.1 as shown below:
The view code:
The in the controller in $this->request->data:
And in $_POST:
You can also give the two submits different names:
This way you can differ them in the $_POST or $this->request->data, because the keys will be the submits' names:
Then to determine which button is pressed you can use a simple isset($_POST['']) or over $this->request->data ?
in 2.0 there is no
$this->params['form']
anymore all form helper posted fields end up in$this->data
(which makes more sense anyway)so
note that !empty() is better here as well.
PS: you can use my enhanced upgrade shell to replace it in your code: https://github.com/dereuromark/upgrade
its the command
(https://github.com/dereuromark/upgrade/blob/master/Console/Command/UpgradeShell.php#L833)