Skip to content

Commit

Permalink
Merge pull request codeigniter4#7818 from kenjis/fix-set_checkbox
Browse files Browse the repository at this point in the history
fix: `set_checkbox()` checks unchecked checkbox
  • Loading branch information
kenjis authored Aug 22, 2023
2 parents cfd8898 + f2f7dcf commit 411a9bb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
5 changes: 4 additions & 1 deletion system/Helpers/form_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -629,8 +629,11 @@ function set_checkbox(string $field, string $value = '', bool $default = false):
return '';
}

$session = Services::session();
$hasOldInput = $session->has('_ci_old_input');

// Unchecked checkbox and radio inputs are not even submitted by browsers ...
if ((string) $input === '0' || ! empty($request->getPost()) || ! empty(old($field))) {
if ((string) $input === '0' || ! empty($request->getPost()) || $hasOldInput) {
return ($input === $value) ? ' checked="checked"' : '';
}

Expand Down
23 changes: 23 additions & 0 deletions tests/system/Helpers/FormHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,29 @@ public function testSetCheckboxWithValueZero(): void
$this->assertSame(' checked="checked"', set_checkbox('foo', '0', true));
}

/**
* @see https://github.com/codeigniter4/CodeIgniter4/issues/7814
*/
public function testSetCheckboxWithUnchecked(): void
{
$_SESSION = [
'_ci_old_input' => [
'post' => [
],
],
];

$this->assertSame(
'',
set_checkbox('fruit', 'apple', true)
);

$this->assertSame(
'',
set_checkbox('fruit', 'apple')
);
}

/**
* @runInSeparateProcess
* @preserveGlobalState disabled
Expand Down

0 comments on commit 411a9bb

Please sign in to comment.