我正在构建与'#type' => 'checkboxes'一起使用表单元素的东西。
我希望它是可重用的,所以它应该接受任何作为PHP数组键(整数和非整数字符串)工作的选项值。
$form['checkboxes'] = [
'#type' => 'checkboxes',
'#options' => [
0 => 'zero',
'' => 'empty string',
' ' => 'space',
'other' => 'Other',
],
];但是,值0 (零)和'' (空字符串)似乎存在问题。
即使选中了“”或“0”的复选框,$element['#value']数组中的值也会消失,例如,当检查自定义的“#element_validate”回调时。
$element['#value'] === [
# '' and 0 are gone, even if they were checked.
' ' => ' ',
'other' => 'other',
];有趣的是,$_POST仍然包含这些值,其中空格和空字符串的行为方式类似于通过[]插入数组。我想这是由于POST数据的发送方式所致。
$_POST['checkboxes'] === [
0 => '0',
1 => '',
2 => ' ',
'other' => 'other',
];我可以想象为什么会发生这一切,但有解决办法吗?
编辑:代码片段的前一个版本是误导的,对不起。我混淆了$_POST和原始的‘#选项’数组。
发布于 2019-02-22 20:19:41
通过在复选框元素上添加“#element_validate”处理程序,我成功地防止了这个问题。
下面的代码是我所做工作的简化版本,由您来微调。
$element['#element_validate'][] = '_MYMODULE_checkboxes_validate';
function _MYMODULE_checkboxes_validate(array &$element, array &$form_state) {
// The form value already has the format $[$id] = $id, mostly.
// However, if trim($id) === '', the array key will be an integer increment.
$value = $element['#value'];
// Make sure it has the expected format.
if (!is_array($value) || [] === $value) {
$ids = [];
}
else {
// Get rid of integer keys for empty-ish string ids.
$ids = array_combine($value, $value);
}
// Remove dangling * => 0 entries.
form_set_value($element, $ids, $form_state);
}注意:如果安装了价值_是模块,由于_value_is_disabled_options_value_callback(),空的ish值将始终未设置。
https://drupal.stackexchange.com/questions/276825
复制相似问题