diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index c553bddee2..7f8f191a3a 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -629,8 +629,11 @@ if (! function_exists('set_checkbox')) { 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"' : ''; } diff --git a/tests/system/Helpers/FormHelperTest.php b/tests/system/Helpers/FormHelperTest.php index cbd3618752..8ed1bdeb72 100644 --- a/tests/system/Helpers/FormHelperTest.php +++ b/tests/system/Helpers/FormHelperTest.php @@ -866,6 +866,29 @@ final class FormHelperTest extends CIUnitTestCase $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