Yii - Two submit buttons, one form. Which one was pressed?
You’ve got two buttons on a form that call the same controller action. How can you tell in the action which button was pressed? We’ll pretend our buttons are named button-one and button-two
and the controller action is actionUpdate
. Using the isset
function we can determine which button was pressed.
```phppublic function actionUpdate($id) { if(isset($_POST[‘button-one’])) { // Button one was pressed } else if ( isset($_POST[‘button-two’]) ) { // Button two was pressed } }
A much cleaner way (in my opinion), is to create two separate controller actions. Then use `Html` helper to create two links styled like buttons that will call them.
```php...
public function actionUpdateOne($id) {
...
}
public function actionUpdateTwo($id) {
...
}
...
<div class="form-group">
<?= Html::a('Edit One', ['/site/update-one', 'id' => 11], ['class'=>'btn btn-success']) ?>
<?= Html::a('Edit Two', ['/site/update-two', 'id' => 22], ['class'=>'btn btn-success']) ?>
...
Chances are you’ll want to pass some parameters to your actions; The example above shows how to do so with a parameter called id
.