I have a simple form as below, with two buttons that have ‘submit’ attribute. If the method attribute of the form is POST, then clicking on each button will submit to its ‘submit’ URL (this is right). But if the method attribute is GET, then clicking button always submits to the URL of the form. Is this a bug?
I’m using yii 1.1.13
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'search-form',
'action' => array('index'),
'method' => 'get',
));
echo CHtml::button('Search 1', array(
'submit' => array('search1'),
));
echo ' ';
echo CHtml::button('Search 2', array(
'submit' => array('search2'),
));
$this->endWidget();
?>
Thanks.
Hi,
You can use
echo CHtml::submitButton('Search 1');
Same problem with CHtml::submitButton().
I found the cause of the problem. If form method is set to "get", then CActiveForm widget (also the CHtml::beginForm() method) creates a hidden field named "r" to set the route parameter. So when the form is submit (via the "submit" attribute of CHtml::button()), the "r" parameter is not changed so that the submitted URL is not changed.
The solution is to set "onclick" attribute of CHtml::button().
The simple and dirty way is redirecting to a URL when clicking on the button. This will ignore the form parameters.
The general way is setting the parameter "r" then submitting the form.
Sample code:
<script type="text/javascript">
/**
* @param element Submit button.
* @param String route The route string to be set to "r" parameter.
* Set the "r" parameter then submit the form.
*/
function submitForm(element, route) {
// Get the form.
var form = $(element).parents('form')[0];
form = $(form);
form.find('input[name=r]').val(route); // Set r parameter.
form.submit(); // Submit form.
}
/**
* Redirect to specified url.
* @param String url
*/
function redirectTo(url) {
window.location.href = url;
}
</script>
<?php
/**
* Create a route string.
* Code adopted from CController#createUrl().
* @param Controller $controller
* @param string $route the URL route. @see CController#createUrl()
* @return String the constructed route.
*/
function createRoute($controller, $route) {
if($route==='')
$route=$controller->getId().'/'.$controller->getAction()->getId();
elseif(strpos($route,'/')===false)
$route=$controller->getId().'/'.$route;
if($route[0]!=='/' && ($module=$controller->getModule())!==null)
$route=$module->getId().'/'.$route;
return trim($route, '/');
}
?>
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'search-form',
'method' => 'get',
));
// Another form parameter.
echo CHtml::hiddenField('h', "another parameter");
// General way.
echo CHtml::button('Search 1', array(
'onclick' => 'submitForm(this, "' . createRoute($this, 'search1') . '")',
));
echo ' ';
// Simple and dirty way.
echo CHtml::button('Search 2', array(
'onclick' => 'redirectTo("' . $this->createUrl('search2', array('h' => 'another parameter')) . '")',
));
$this->endWidget();
?>