Skip to content

Commit

Permalink
ENH Allow better subclassing of MoneyField
Browse files Browse the repository at this point in the history
Move generation of NumberField from constructor to method to allow override in subclass.

Addded test for MoneyField
  • Loading branch information
beerbohmdo committed Feb 19, 2024
1 parent bcbbfdd commit ada23af
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/Forms/MoneyField.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,7 @@ public function getAmountField()
public function __construct($name, $title = null, $value = "")
{
$this->setName($name);
$this->fieldAmount = NumericField::create(
"{$name}[Amount]",
_t('SilverStripe\\Forms\\MoneyField.FIELDLABELAMOUNT', 'Amount')
)
->setScale(2);
$this->buildAmountField();
$this->buildCurrencyField();

parent::__construct($name, $title, $value);
Expand All @@ -75,6 +71,20 @@ public function __clone()
$this->fieldCurrency = clone $this->fieldCurrency;
}

/**
* Builds a field to input the amount of money
*
* @return void
*/
protected function buildAmountField(): void
{
$this->fieldAmount = NumericField::create(
$this->name . '[Amount]',
_t('SilverStripe\\Forms\\MoneyField.FIELDLABELAMOUNT', 'Amount')
)
->setScale(2);
}

/**
* Builds a new currency field based on the allowed currencies configured
*
Expand Down
25 changes: 25 additions & 0 deletions tests/php/Forms/MoneyFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

namespace SilverStripe\Forms\Tests;

use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\NumericField;
use SilverStripe\Forms\RequiredFields;
use SilverStripe\Forms\Tests\MoneyFieldTest\CustomSetter_Object;
use SilverStripe\Forms\Tests\MoneyFieldTest\TestObject;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\FieldType\DBMoney;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Forms\MoneyField;
Expand Down Expand Up @@ -127,4 +130,26 @@ public function testValidation()
]);
$this->assertFalse($field->validate($validator));
}

public function testCurrencyField(): void
{
$field = new MoneyField('Money');
$field->setAllowedCurrencies(['NZD', 'USD']);

$this->assertInstanceOf(DropdownField::class, $field->getCurrencyField());
$this->assertEquals('Money[Currency]', $field->getCurrencyField()->getName());

$field->setAllowedCurrencies(['USD']);

$this->assertInstanceOf(TextField::class, $field->getCurrencyField());
$this->assertEquals('Money[Currency]', $field->getCurrencyField()->getName());
}

public function testAmountField(): void
{
$field = new MoneyField('Money');
$this->assertInstanceOf(NumericField::class, $field->getAmountField());
$this->assertEquals(2, $field->getAmountField()->getScale());
$this->assertEquals('Money[Amount]', $field->getCurrencyField()->getName());
}
}

0 comments on commit ada23af

Please sign in to comment.