Skip to content

Commit bd99bb5

Browse files
committed
generic bool type check in checkbox control
1 parent f4f8de1 commit bd99bb5

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

src/Form/Control/Checkbox.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,6 @@ public function __construct($label = [])
3333

3434
protected function init(): void
3535
{
36-
// TODO exception should be generalized for type acceptable for any form control
37-
if ($this->entityField && $this->entityField->getField()->type !== 'boolean') {
38-
throw (new Exception('Checkbox form control requires field with boolean type'))
39-
->addMoreInfo('type', $this->entityField->getField()->type);
40-
}
41-
4236
parent::init();
4337

4438
// checkboxes are annoying because they don't send value when they are
@@ -57,6 +51,12 @@ protected function renderView(): void
5751
$this->template->set('Content', $this->label);
5852
}
5953

54+
if ($this->entityField && !is_bool($this->entityField->get() ?? false)) {
55+
throw (new Exception('Checkbox form control requires field with boolean type'))
56+
->addMoreInfo('type', $this->entityField->getField()->type)
57+
->addMoreInfo('value', $this->entityField->get());
58+
}
59+
6060
if ($this->entityField ? $this->entityField->get() : $this->content) {
6161
$this->template->dangerouslySetHtml('checked', 'checked="checked"');
6262
}

tests/FormTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Atk4\Core\Phpunit\TestCase;
88
use Atk4\Data\Model;
9+
use Atk4\Data\Model\EntityFieldPair;
910
use Atk4\Data\ValidationException;
1011
use Atk4\Ui\App;
1112
use Atk4\Ui\Callback;
@@ -226,6 +227,22 @@ public function testNoDisabledAttrWithHiddenType(): void
226227
self::assertStringNotContainsString('readonly', $input->render());
227228
}
228229

230+
public function testCheckboxWithNonBooleanException(): void
231+
{
232+
$input = new Form\Control\Checkbox();
233+
$input->setApp($this->createApp());
234+
$input->invokeInit();
235+
236+
$m = new Model();
237+
$m->addField('foo');
238+
$input->entityField = new EntityFieldPair($m->createEntity(), 'foo');
239+
$input->entityField->set('1');
240+
241+
$this->expectException(Exception::class);
242+
$this->expectExceptionMessage('Checkbox form control requires field with boolean type');
243+
$input->render();
244+
}
245+
229246
public function testUploadNoUploadCallbackException(): void
230247
{
231248
$input = new Form\Control\Upload();

0 commit comments

Comments
 (0)