我正在使用CakePHP构建的应用程序中的几个表单字段收集其值的百分比。我希望用户能够以熟悉的百分比(24.5%)格式查看和编辑百分比,但我希望将其存储为十进制(.245)格式,以便简化计算逻辑。由于有几个这样的字段,我宁愿不必为每个百分比字段编写转换逻辑到控制器中。
有人知道自动执行此转换的简单解决方案吗?还是我卡住了编写自定义助手/行为来解决此问题?
<解决方案/strong>
我最后写了一个jQuery插件来处理这个问题。这是给任何将来可能需要它的人:
/**
* Input Percent
*
* Percentages are tricky to input because users like seeing them as 24.5%, but
* when using them in calculation their value is actually .245. This plugin
* takes a supplied field and automatically creates a percentage input.
*
* It works by taking an input element and creating a hidden input with the same
* name immediately following it in the DOM. This has the effect of submitting
* the proper value instead of the human only one. An onchange method is then
* bound to the original input in order to keep the two synced.
*
* Potential Caveats:
* * There will be two inputs with the same name. Make sure anything you
* script against this field is prepared to handle that.
*
* @author Brad Koch <kochb@aedisit.com>
*/
(function($) {
$.fn.inputPercent = function() {
return this.each(function() {
var display_field = this;
var value_field = $('<input type="hidden" />').get(0);
// Initialize and attach the hidden input.
$(value_field).attr('name', $(this).attr('name'));
$(value_field).val($(display_field).val());
$(display_field).after(value_field);
$(display_field).after('%');
// Convert the display field's proper percent value into the display format.
if (isFinite($(display_field).val())) {
$(display_field).val($(display_field).val() * 100);
}
// Enable synchronization between the two.
$(this).bind('change', function () {
var value = $(display_field).val();
// Handle non-numeric values.
if (isFinite(value)) {
$(value_field).val(value / 100);
} else {
$(value_field).val(value);
}
});
});
};
})(jQuery);
用法:
$('input.percent').inputPercent();
你可以写一些简单的javascript(使用任何你喜欢的框架,或者普通的js)在提交前用一个类#percentage转换字段。
或者,也处理用户没有javascript;在模型中,添加beforeSave()方法,检查数字是否为<如果不是,则除以100。
如果NumberHelper不能提供帮助,你也可以添加一个简单的组件或帮助器来将内部数字转换回百分比以供显示。
已经有了一个帮助器——NumberHelper
http://book.cakephp.org/view/1455/toPercentage我发现的唯一缺点是,如果您将数据存储为百分数的十进制表示(即0.045 = 4.5%)而不是实际百分比(即0.045 = 0.045%),那么您必须在转换之前乘以100。
ie:<?php echo $this->Number->toPercentage( 51.5 ); // 51.5% ?>
<?php echo $this->Number->toPercentage( .245 * 100 ); // 24.5% ?>
我最近写了一个插件来转换和json存储在数据库中。https://github.com/dereuromark/tools/blob/master/models/behaviors/jsonable.php
你可以很容易地修改它来转换从和到百分比。你需要一些自定义
afterFind
和
beforeSave
然后将其附加到模型上,如下所示:
$ actas = array('Percentage');