2011-09-26 70 views
2

我使用CakePHP构建的应用程序中的几个表单字段会为它们的值收集百分比。我希望用户能够以熟悉的百分比(24.5%)格式查看和编辑百分比,但为了简化计算逻辑,我希望以十进制(.245)格式存储它。由于有几个这样的字段,我宁愿不必将每个百分比字段的转换逻辑写入控制器。自动转换百分比输入值

是否有人知道自动执行此转换的简单解决方案,还是我坚持编写自定义帮助程序/行为来解决此问题?

解决方案

我最后写一个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 <[email protected]> 
*/ 
(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(); 

回答

2

你可以写一些简单的JavaScript(使用任何你喜欢的框架,或纯JS),以场转换与类#percentage的只是提交之前。

另外,也处理没有JavaScript的用户;在模型中,添加beforeSave()方法,检查数字是否为< 1,如果不是,则除以100.

您也可以添加一个简单的组件或帮助程序将内部数字转换回百分比用于显示,如果NumberHelper不能帮助。

+0

这就是我最终做的。我在这个问题上发布了这个实现。 –

2

已经有一个帮手这 - NumberHelper

http://book.cakephp.org/view/1455/toPercentage

的我发现的唯一缺点是,如果您将数据存储为百分比的十进制表示(即.045 = 4.5%)而不是实际百分比(即.045 = .045%),那么您转换前必须乘以100。

即:

<?php echo $this->Number->toPercentage(51.5); // 51.5% ?> 
<?php echo $this->Number->toPercentage(.245 * 100); // 24.5% ?> 
+2

另一种选择(如果数据来自查询中的主表,即不是相关表),则使用virtualField。因此,您只需添加一个采用原始字段并即时计算百分比字段的virtualField条目即可。 –

+0

我会一直在视图中使用助手 - 按需。为什么使用虚拟字段如果百分比可能不会在视图中的任何位置使用? – mark

+1

此解决方案的格式化部分已关闭,但只处理显示逻辑..我仍然必须自行完成转换。不幸的是虚拟领域不能解决问题,因为还有一个报告应用程序正在从这个数据库中读取数据。马克是对的;某些辅助/ JS输入小部件是我需要的。 –