diff --git a/forms/MoneyField.php b/forms/MoneyField.php index dc2a23321..a05aee479 100644 --- a/forms/MoneyField.php +++ b/forms/MoneyField.php @@ -85,10 +85,26 @@ class MoneyField extends FormField { // and subsequent save operations } + /** + * 30/06/2009 - Enhancement: + * SaveInto checks if set-methods are available and use them + * instead of setting the values in the money class directly. saveInto + * initiates a new Money class object to pass through the values to the setter + * method. + * + * (see @link MoneyFieldTest_CustomSetter_Object for more information) + */ function saveInto($dataObject) { $fieldName = $this->name; - $dataObject->$fieldName->setCurrency($this->fieldCurrency->Value()); - $dataObject->$fieldName->setAmount($this->fieldAmount->Value()); + if($dataObject->hasMethod("set$fieldName")) { + $dataObject->$fieldName = DBField::create('Money', array( + "Currency" => $this->fieldCurrency->Value(), + "Amount" => $this->fieldAmount->Value() + )); + } else { + $dataObject->$fieldName->setCurrency($this->fieldCurrency->Value()); + $dataObject->$fieldName->setAmount($this->fieldAmount->Value()); + } } /** diff --git a/tests/forms/MoneyFieldTest.php b/tests/forms/MoneyFieldTest.php index 87f2391de..58705e142 100644 --- a/tests/forms/MoneyFieldTest.php +++ b/tests/forms/MoneyFieldTest.php @@ -43,6 +43,22 @@ class MoneyFieldTest extends SapphireTest { $this->assertEquals($o->MyMoney->getAmount(), 1.23); $this->assertEquals($o->MyMoney->getCurrency(), 'EUR'); } + + /** + * This UT tests if saveInto used customised getters/setters correctly. + * Saving values for CustomMoney shall go through the setCustomMoney_Test + * setter method and double the value. + */ + function testSetValueViaSetter() { + $o = new MoneyFieldTest_CustomSetter_Object(); + + $f = new MoneyField('CustomMoney', 'Test Money Field'); + $f->setValue(array('Currency'=>'EUR','Amount'=>1.23)); + + $f->saveInto($o); + $this->assertEquals($o->MyMoney->getAmount(), (2 * 1.23) ); + $this->assertEquals($o->MyMoney->getCurrency(), 'EUR'); + } } class MoneyFieldTest_Object extends DataObject implements TestOnly { @@ -50,4 +66,28 @@ class MoneyFieldTest_Object extends DataObject implements TestOnly { 'MyMoney' => 'Money', ); } + +/** + * Customised class, implementing custom getter and setter methods for + * MyMoney. + */ +class MoneyFieldTest_CustomSetter_Object extends DataObject implements TestOnly { + static $db = array( + 'MyMoney' => 'Money', + ); + + function getCustomMoney() { + return $this->MyMoney->getValue(); + } + + function setCustomMoney($value) { + + $newAmount = $value->getAmount() * 2; + $this->MyMoney->setAmount($newAmount); + + $newAmount = $value->getAmount() * 2; + $this->MyMoney->setCurrency($value->getCurrency()); + + } +} ?> \ No newline at end of file