silverstripe-framework/model/FieldType/DBPercentage.php

48 lines
986 B
PHP
Raw Normal View History

<?php
namespace SilverStripe\Model\FieldType;
/**
* Represents a decimal field from 0-1 containing a percentage value.
2014-08-15 08:53:05 +02:00
*
* Example instantiation in {@link DataObject::$db}:
* <code>
* static $db = array(
* "SuccessRatio" => "Percentage",
* "ReallyAccurate" => "Percentage(6)",
* );
* </code>
2014-08-15 08:53:05 +02:00
*
* @package framework
* @subpackage model
*/
class DBPercentage extends DBDecimal {
2014-08-15 08:53:05 +02:00
/**
* Create a new Decimal field.
*/
public function __construct($name = null, $precision = 4) {
if(!$precision) $precision = 4;
2014-08-15 08:53:05 +02:00
parent::__construct($name, $precision + 1, $precision);
}
2014-08-15 08:53:05 +02:00
/**
* Returns the number, expressed as a percentage. For example, “36.30%
*/
public function Nice() {
return number_format($this->value * 100, $this->decimalSize - 2) . '%';
}
2014-08-15 08:53:05 +02:00
public function saveInto($dataObject) {
parent::saveInto($dataObject);
2014-08-15 08:53:05 +02:00
$fieldName = $this->name;
if($fieldName && $dataObject->$fieldName > 1.0) {
$dataObject->$fieldName = 1.0;
}
}
}