Skip to content
Permalink
Browse files

Expand logic to detect checked.

Since value is a primitive attribute, re-using it for checked/selected
state is a bit of a bad idea. This will probably lead to refactoring in
selectbox and radio as well.
  • Loading branch information...
markstory committed Jan 12, 2014
1 parent 32b75e8 commit 567a65c1b0cfa94180d8672e032f3b9bd2381a1a
Showing with 74 additions and 2 deletions.
  1. +21 −1 src/View/Input/Checkbox.php
  2. +53 −1 tests/TestCase/View/Input/CheckboxTest.php
@@ -46,12 +46,16 @@ public function render($data) {
$data += [
'name' => '',
'value' => 1,
'selected' => null,
'checked' => false,
'disabled' => false,
];
if ($this->_isChecked($data)) {
$data['checked'] = true;
}
$attrs = $this->_templates->formatAttributes(
$data,
['name', 'value']
['name', 'value', 'selected']
);
return $this->_templates->format('checkbox', [
@@ -61,4 +65,20 @@ public function render($data) {
]);
}
/**
* Check whether or not the checkbox should be checked.
*
* @param array $data Data to look at and determine checked state.
* @return boolean
*/
protected function _isChecked($data) {
if (!empty($data['checked'])) {
return true;
}
if ((string)$data['selected'] === (string)$data['value']) {
return true;
}
return false;
}
}
@@ -54,7 +54,7 @@ public function testRenderSimple() {
$data = [
'name' => 'Comment[spam]',
'value' => 99
'value' => 99,
];
$result = $checkbox->render($data);
$expected = [
@@ -112,6 +112,58 @@ public function testRenderChecked() {
]
];
$this->assertTags($result, $expected);
$data = [
'name' => 'Comment[spam]',
'value' => 1,
'selected' => 1,
];
$result = $checkbox->render($data);
$this->assertTags($result, $expected);
$data['selected'] = '1';
$result = $checkbox->render($data);
$this->assertTags($result, $expected);
$data = [
'name' => 'Comment[spam]',
'value' => 1,
'selected' => '1x',
];
$result = $checkbox->render($data);
$expected = [
'input' => [
'type' => 'checkbox',
'name' => 'Comment[spam]',
'value' => 1,
]
];
$this->assertTags($result, $expected);
}
/**
* Test rendering checked checkboxes with value.
*
* @return void
*/
public function testRenderCheckedValue() {
$checkbox = new Checkbox($this->templates);
$data = [
'name' => 'Comment[spam]',
'value' => 1,
'checked' => 1,
];
$result = $checkbox->render($data);
$expected = [
'input' => [
'type' => 'checkbox',
'name' => 'Comment[spam]',
'value' => 1,
'checked' => 'checked',
]
];
$this->assertTags($result, $expected);
}
}

0 comments on commit 567a65c

Please sign in to comment.
You can’t perform that action at this time.