silverstripe-framework/src/Forms/CurrencyField.php

82 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace SilverStripe\Forms;
use SilverStripe\ORM\FieldType\DBCurrency;
/**
* Renders a text field, validating its input as a currency.
* Limited to US-centric formats, including a hardcoded currency
* symbol and decimal separators.
* See {@link MoneyField} for a more flexible implementation.
*
* @todo Add localization support, see http://open.silverstripe.com/ticket/2931
*/
2016-11-29 00:31:16 +01:00
class CurrencyField extends TextField
{
/**
* allows the value to be set. removes the first character
* if it is not a number (probably a currency symbol)
*
* @param mixed $value
* @param mixed $data
2016-11-29 00:31:16 +01:00
* @return $this
*/
public function setValue($value, $data = null)
2016-11-29 00:31:16 +01:00
{
if (!$value) {
$value = 0.00;
2016-11-29 00:31:16 +01:00
}
2017-02-22 04:14:53 +01:00
$this->value = DBCurrency::config()->uninherited('currency_symbol')
. number_format((double)preg_replace('/[^0-9.\-]/', '', $value), 2);
2016-11-29 00:31:16 +01:00
return $this;
}
/**
* Overwrite the datavalue before saving to the db ;-)
* return 0.00 if no value, or value is non-numeric
*/
public function dataValue()
{
if ($this->value) {
return preg_replace('/[^0-9.\-]/', '', $this->value);
} else {
return 0.00;
}
}
2016-11-29 00:31:16 +01:00
public function Type()
{
return 'currency text';
}
2016-11-29 00:31:16 +01:00
/**
* Create a new class for this field
*/
public function performReadonlyTransformation()
{
return $this->castedCopy('SilverStripe\\Forms\\CurrencyField_Readonly');
}
2016-11-29 00:31:16 +01:00
public function validate($validator)
{
2017-02-22 04:14:53 +01:00
$currencySymbol = preg_quote(DBCurrency::config()->uninherited('currency_symbol'));
2018-01-16 19:39:30 +01:00
$regex = '/^\s*(\-?' . $currencySymbol . '?|' . $currencySymbol . '\-?)?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?\s*$/';
2016-11-29 00:31:16 +01:00
if (!empty($this->value) && !preg_match($regex, $this->value)) {
$validator->validationError(
$this->name,
2017-04-20 03:15:24 +02:00
_t('SilverStripe\\Forms\\Form.VALIDCURRENCY', "Please enter a valid currency"),
2016-11-29 00:31:16 +01:00
"validation"
);
return false;
}
return true;
}
2016-10-28 05:22:58 +02:00
2016-11-29 00:31:16 +01:00
public function getSchemaValidation()
{
$rules = parent::getSchemaValidation();
$rules['currency'] = true;
return $rules;
}
}