FIX: Resolve issue when selected value is zero. (#2530)

$this->value is stored as string internally. In
the special case that the option value is 0, the
type comparison fails to resolve 0 == '0',
see http://www.php.net/manual/en/types.comparisons.php.
This commit is contained in:
Will Rossiter 2014-01-11 13:25:25 +13:00
parent 6fae1e6392
commit f433b5000f
2 changed files with 52 additions and 2 deletions

View File

@ -164,7 +164,12 @@ class DropdownField extends FormField {
$selected = true;
} else {
// check against value, fallback to a type check comparison when !value
$selected = ($value) ? $value == $this->value : $value === $this->value;
if($value) {
$selected = ($value == $this->value);
} else {
$selected = ($value === $this->value) || (((string) $value) === ((string) $this->value));
}
$this->isSelected = $selected;
}

View File

@ -79,7 +79,52 @@ class DropdownFieldTest extends SapphireTest {
)
);
}
public function testStringZeroValueSelectedOptionBehaviour() {
$field = new DropdownField('Field', null, array(
'-1' => 'some negative',
'0' => 'none',
'1' => 'one',
'2+' => 'two or more'
), '0');
$selectedOptions = $this->findSelectedOptionElements($field->Field());
$this->assertEquals((string) $selectedOptions[0], 'none', 'The selected option is "none"');
$field = new DropdownField('Field', null, array(
'-1' => 'some negative',
'0' => 'none',
'1' => 'one',
'2+' => 'two or more'
), 0);
$selectedOptions = $this->findSelectedOptionElements($field->Field());
$this->assertEquals((string) $selectedOptions[0], 'none', 'The selected option is "none"');
}
public function testStringOneValueSelectedOptionBehaviour() {
$field = new DropdownField('Field', null, array(
'-1' => 'some negative',
'0' => 'none',
'1' => 'one',
'2+' => 'two or more'
), '1');
$selectedOptions = $this->findSelectedOptionElements($field->Field());
$this->assertEquals((string) $selectedOptions[0], 'one', 'The selected option is "one"');
$field = new DropdownField('Field', null, array(
'-1' => 'some negative',
'0' => 'none',
'1' => 'one',
'2+' => 'two or more'
), 1);
$selectedOptions = $this->findSelectedOptionElements($field->Field());
$this->assertEquals((string) $selectedOptions[0], 'one', 'The selected option is "one"');
}
public function testNumberOfSelectOptionsAvailable() {
/* Create a field with a blank value */
$field = $this->createDropdownField('(Any)');