我正试图解决一个无法理解的表单提交问题。当我第一次提交表单时,在更改下拉列表的值后,$this->request->data
数组为空。如果我再次提交,我会看到我的期望。每当我更改表单上的任何一个下拉项时,都会发生这种情况。
这是表格:
<?php
echo $this->Form->create('Refine', array('url' => '/ServiceDirectoryResults/refine'));
echo $this->Form->input('state', array(
'type' => 'select',
'label' => 'State',
'options' => $all_states,
'selected' => array('state_selected', $state_selected),
'id' => 'state',
));
echo $this->Form->input('solution', array(
'type' => 'select',
'label' => 'Solution',
'options' => $solutions,
'selected' => array('selected', $solution),
'id' => 'solutions',
));
echo $this->Form->input('region', array(
'before' => '<fieldset id="Region">',
'multiple' => 'checkbox',
'options' => $regions,
'selected' => $reg_selected,
'after' => '</fieldset>'
));
echo $this->Form->input('tags', array(
'before' => '<fieldset id="TagBox">',
'multiple' => 'checkbox',
'options' => $narrow,
'selected' => $tag_selected,
'after' => '</fieldset>'
));
echo $this->Form->end('Refine Search');
?>
表单呈现良好。如果更改了状态或解决方案下拉列表并提交了表单,则$this->request->data
数组为空。如果我第二次提交,并且不做任何更改,数组将包含我希望看到的内容。
在我的控制器中,我有
if(isset($this->request->data['Refine']['state']))
{
$state = $this->request->data['Refine']['state'];
}
显然,如果数组是空的,那么在第一次提交表单时,我在状态变量中什么也得不到。
如果有人能揭露这种行为,我将不胜感激。我在形式创作上做错了什么吗?
根据要求,这里是与此表单一起使用的js。其想法是,它只需要在"全部"复选框的情况下设置或清除复选框,这是为控制器中的区域和标记创建的第一个复选框。
$(document).ready(function(){
$("#RefineRegion0").click(function(){
if ($("#Region #RefineRegion0").is(':checked')) {
$("#Region input[type=checkbox]").each(function (e) {
$(this).prop("checked", true);
});
} else {
$("#Region input[type=checkbox]").each(function (e) {
$(this).prop("checked", false);
});
}
});
$("#RefineTags0").click(function(){
if ($("#TagBox #RefineTags0").is(':checked')) {
$("#TagBox input[type=checkbox]").each(function (e) {
$(this).prop("checked", true);
});
} else {
$("#TagBox input[type=checkbox]").each(function (e) {
$(this).prop("checked", false);
});
}
});
$("#RefineViewForm").submit(function(){
if($('#state').val() == "" || $('#solutions').val() == ""){
alert("Please select a State and Solution before continuing")
}
});
});
希望对有所帮助
我注意到两件事:
1) 表单的url:controllers名称小写并加下划线:service_directory_results。请参阅cakepp名称转换:http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html。但我认为最好使用url的数组,这样你的路线可以匹配:
echo $this->Form->create('Refine', array('url' => array('controller' => 'service_directory_results', 'action' => 'refine')));
2) 在你的Js上,如果这些字段为空,不要发送添加后返回false;(也缺少一个;)
$("#RefineViewForm").submit(function(){
if($('#state').val() == "" || $('#solutions').val() == ""){
alert("Please select a State and Solution before continuing");
return false;
}
});