简体   繁体   中英

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?

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), ie 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'])

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM