在 CakePHP 3.4 中格式化数据以保存和显示

问题描述 投票:0回答:1

我的表中有一个名为 value 的字段,它是一个大小为 11 的 INT 字段(MySQL)。它存储货币值的数据,没有小数点和千位分隔符。例如:4.658,85 将变为 465885(巴西数字格式)。

假设我想保存值 1,200.50:

我有一个带有 jQuery 掩码的输入字段,它将以 1.200,50 的格式存储该值。

那么,为了拯救它,我必须这样做:

// In the Controller
        if ($this->request->is(['post'])) {
            // This will convert 1.200,50 to 120050
            $this->request->data['value'] = str_replace([',', '.'], '', $this->request->data['value']);

            $this->Entity->patchEntity($entity, $this->request->getData());

            if ($this->Entity->save($entity)) {
                // Entity saved...
            }
        }

之后,要在视图中显示格式化的值,我必须这样做:

<!-- In a View -->
<p><?php echo number_format($data['value'] / 10, 2, ',', '.') ?></p>

编辑实体时,我还必须调用格式化函数,因为使用 jQuery Mask 输入:

// When editing. In the Controller
        if ($this->request->is(['get'])) {
            if (!empty($entity['value'])) {
                $this->request->data['value'] = number_format($entity['value'] / 10, 2, ',', '.')
            }
        }

这适用于我的项目,但我认为有一种更好、更专业的方法可以在保存之前和显示该值之前进行此类转换,当我必须在项目中多次调用该字段时,这是一项大量的工作。有人可以帮帮我吗?

php mysql cakephp-3.0
1个回答
0
投票

CakePHP有默认的数字功能,请使用。

示例:

echo $this->Number->format('123456.7890', [
'places' => 2,
'before' => '¥ ',
'after' => ' !' ]);
// Output '¥ 123,456.79 !'

参考链接:https://book.cakephp.org/3.0/en/core-libraries/number.html#formatting-numbers

解决方案1:使用实体创建连接名字和姓氏字段的通用函数

示例代码:

用户实体文件:

class User extends Entity {

protected $_virtual = ['full_name'];

protected function _getFullName() {
    return $this->_properties['first_name'] . ' ' . $this->_properties['last_name'];
}}

查看文件:

<td><?= $input->full_name ?></td>

解决方案2:我们也可以使用beforeMarshal函数

public function beforeMarshal($data,$options) {
foreach ($data as $key => $value) {
        $data[$key] = number_format($value,2);
}}

希望这对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.