Skip to content

Commit

Permalink
Fix boolean values in select widgets.
Browse files Browse the repository at this point in the history
Boolean `false` should be treated like `0` when comparing option values.

Refs #8468
  • Loading branch information
markstory committed Mar 16, 2016
1 parent 61b0902 commit 745f3a3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
44 changes: 44 additions & 0 deletions lib/Cake/Test/Case/View/Helper/FormHelperTest.php
Expand Up @@ -4844,6 +4844,50 @@ public function testSelect() {
$this->assertTags($result, $expected);
}

/**
* testSelect boolean method
*
* @return void
*/
public function testSelectBoolean() {
$result = $this->Form->select(
'Model.field',
array(0 => 'No', 1 => 'Yes'),
array('value' => false, 'empty' => false)
);
$expected = array(
'select' => array('name' => 'data[Model][field]', 'id' => 'ModelField'),
array('option' => array('value' => '0', 'selected' => 'selected')),
'No',
'/option',
array('option' => array('value' => '1')),
'Yes',
'/option',
'/select'
);
$this->assertTags($result, $expected);

$result = $this->Form->select(
'Model.field',
array(0 => 'No', 1 => 'Yes', 2 => 'Yes again'),
array('value' => [false, 2], 'empty' => false)
);
$expected = array(
'select' => array('name' => 'data[Model][field]', 'id' => 'ModelField'),
array('option' => array('value' => '0', 'selected' => 'selected')),
'No',
'/option',
array('option' => array('value' => '1')),
'Yes',
'/option',
array('option' => array('value' => '2', 'selected' => 'selected')),
'Yes again',
'/option',
'/select'
);
$this->assertTags($result, $expected);
}

/**
* test that select() with optiongroups listens to the escape param.
*
Expand Down
5 changes: 5 additions & 0 deletions lib/Cake/View/Helper/FormHelper.php
Expand Up @@ -2781,6 +2781,11 @@ protected function _selectOptions($elements = array(), $parents = array(), $show
$selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
$selectedIsArray = is_array($attributes['value']);

// Cast boolean false into an integer so string comparisons can work.
if ($attributes['value'] === false) {
$attributes['value'] = 0;
}

$this->_domIdSuffixes = array();
foreach ($elements as $name => $title) {
$htmlOptions = array();
Expand Down

0 comments on commit 745f3a3

Please sign in to comment.