kevintich
kevintich

Reputation: 51

Two submit buttons, one form (Yii)

I have two CHtml::submitButton() in my form, namely "Accept" and "Reject". Each of the buttons has a specific ID ... When any of the two are pressed, i would like to trigger an action in my controller. Below are the code snippets.

=========================================================

View

<?php
echo CHtml::beginForm('mycontrollerName/AcceptUserRegistration','get');
?>

<?php echo CHtml::submitButton('Accept', array('id' => 'accept')); ?>
<? echo '&nbsp;&nbsp;&nbsp;'; ?>
<?php echo CHtml::submitButton('Reject', array('id' => 'reject')); ?> 
<?php echo CHtml::endForm(); ?>

========================================================

Controller

public function actionAcceptUserRegistration() {

$value = $_GET['id'];

if($value == "accept"){
//will do something here
}

if($value == "reject"){
//will do something here.
}

}

======================================================================

When i implement it this way. the get value in the controller side is empty. What I'm I doing wrong? Or is there any other way around this?

Upvotes: 1

Views: 8987

Answers (2)

happyhardik
happyhardik

Reputation: 25537

Here is a code example for what you are trying to achive:

VIEW:

<?php
echo CHtml::beginForm('mycontrollerName/AcceptUserRegistration','get');
?>

<?php echo CHtml::submitButton('Accept', array('id' => 'accept', 'name' => 'accept')); ?>
<? echo '&nbsp;&nbsp;&nbsp;'; ?>
<?php echo CHtml::submitButton('Reject', array('id' => 'reject', 'name' => 'reject')); ?> 
<?php echo CHtml::endForm(); ?>

Note: I added the name parameter. As name is not displayed to the user, you can use accept instead of Accept.

CONTROLLER:

public function actionAcceptUserRegistration() {

if(isset($_GET['accept'])) {
     //accepted
} else if(isset($_GET['reject'])) {
     //rejected
}
//I recommend using POST method instead of GET for posting the form.
}

Upvotes: 3

ThiefMaster
ThiefMaster

Reputation: 318478

You forgot to give the submit button a name (unless your framework does some magic which we cannot know about - you should really post the generated HTML code!).

If you do so, the value in $_GET['buttonname'] will be its value (not its id), i.e. Accept or Reject. This becomes pretty messy as soon as you get into i18n, so you might want to use different names for the buttons and then check isset($_GET['buttonname1']) and isset($_GET['buttonname2'])

Upvotes: 4

Related Questions