【发布时间】:2014-07-19 19:09:49
【问题描述】:
我在使用复选框时发现了一个问题。
我用这样的默认值加载我的表单:
//Defaults for this template
$default['video'] = '';
$default['height'] = '';
$default['width'] = '';
$default['codec'] = '';
$default['time'] = '0';
$default['audio'] = '';
$default['video_id'] = '';
$default['filename_machine'] = '';
//in this template we also use x pos and y pos, but these depend on screen layout ie. not stored on entity.
$data = (array)$data + (array)$default;
if ($data['audio']=='on') {
$audio = 'checked';
}
else {
$audio = '';
}
<td>
Spela upp ljud? <input type='checkbox' name='data_audio' $audio />
</td>
现在,如果默认情况下没有选中一个框,这很好用,但是如果默认值是选中一个框,那么即使用户取消选中该框,该框也会显示为选中状态,保存表单然后回去编辑实体。
我认为一种方法是不使用复选框作为实际保存的表单字段,而是在后面使用隐藏字段,并且仅使用复选框在该字段中设置值“on”或“off”,或者类似的东西。但是还有很多额外的工作。
我以这种方式默认设置的这些特定表单字段由 jQuery 序列化保存,因此我没有一个很好的方法来单步执行和基于类型等操作字段(例如“如果复选框未选中,则设置值'取消选中'”或类似的东西..),否则我想这将是一种方法。
有没有我没想到的更聪明的把戏?
更新
这就是我保存所有以数据为前缀的表单字段的方式_
在提交之前我首先这样做:
var myChunk = $( '#contentForm' ).serialize();
$( "#serialized" ).val( myChunk );
然后,在php中接收表单:
//Get the custom data fields
$serialized = $this->unserializeForm( $request->request->get('serialized') );
$jsonArray = $this->getDataFields($serialized,true); //init the array that will become the json
$dataArray = $this->getDataFields($serialized); //init the array that will becom the one-dimensional array (currently in use)
这是 getDataFields 的样子,也许我可以在这里为复选框字段添加一些额外的过滤...
private function getDataFields($serialized,$toJson=false) {
$myArray = array();
foreach($serialized as $i) {
$label = $i[0];
$value = $i[1];
//find only the data fields (prepended with "data_", skip rest of form)
if(substr($label,0,5) == 'data_') {
//discard the "data_" part of the label
$label = substr($label,5);
if($toJson == true) {
//we're preparing data to be stored as json so we use a multidimensional for better overview.
//see if there is a subgroup to the label (ie. data_BACKGROUND_color or such)
if (strpos($label,'_') !== false) {
//echo 'har undergrupp <br />';
$parts = explode("_", $label); //split label
$group = $parts[0];
$label = $parts[1];
$myArray[$group][$label] = $value; //organize into group and label
}
else {
//echo 'har inte undergrupp <br />';
$myArray[$label] = $value;
}
}
else {
//we're storing data in a plain array
$myArray[$label] = $value;
}
}
}
return $myArray;
}
【问题讨论】:
-
您如何阅读
data_audio值?表单提交后.. -
您还需要在 php 中读取之前设置一些值,例如 ..
<input type='checkbox' name='data_audio' $audio value='on' /> -
$audio 将包含 "checked" 如果打开,那么你的 value="on" 是多余的?
-
您可以尝试打印变量内容
$serialized并粘贴到这里吗?我确定如果未设置该值,那么它返回 null .. fordata_audio -
hmm.. 根据 jQuery 网站本身的演示,序列化字符串中确实省略了未选中的复选框。这对我不利……有什么办法可以强制包含?见api.jquery.com/serialize