1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Ui\Form\Control;
6:
7: use Atk4\Ui\Exception;
8: use Atk4\Ui\Form;
9: use Atk4\Ui\Js\Jquery;
10: use Atk4\Ui\Js\JsExpressionable;
11:
12: class Checkbox extends Form\Control
13: {
14: public $ui = 'checkbox';
15:
16: public $defaultTemplate = 'form/control/checkbox.html';
17:
18: /**
19: * Label appears to the right of the checkbox. If label is not set specifically
20: * then the $caption property will be displayed as a label instead.
21: *
22: * @var string
23: */
24: public $label;
25:
26: public function __construct($label = [])
27: {
28: parent::__construct($label);
29:
30: $this->label = $this->content;
31: $this->content = null;
32: }
33:
34: #[\Override]
35: protected function init(): void
36: {
37: parent::init();
38:
39: // checkboxes are annoying because they don't send value when they are not ticked
40: if ($this->form) {
41: $this->form->onHook(Form::HOOK_LOAD_POST, function (Form $form, array &$postRawData) {
42: if (!isset($postRawData[$this->shortName])) {
43: $postRawData[$this->shortName] = '0';
44: }
45: });
46: }
47: }
48:
49: #[\Override]
50: protected function renderView(): void
51: {
52: if ($this->label) {
53: $this->template->set('Content', $this->label);
54: }
55:
56: if ($this->entityField && !is_bool($this->entityField->get() ?? false)) {
57: throw (new Exception('Checkbox form control requires field with boolean type'))
58: ->addMoreInfo('type', $this->entityField->getField()->type)
59: ->addMoreInfo('value', $this->entityField->get());
60: }
61:
62: if ($this->entityField ? $this->entityField->get() : $this->content) {
63: $this->template->dangerouslySetHtml('checked', 'checked="checked"');
64: }
65:
66: $this->content = null;
67:
68: if ($this->disabled) {
69: $this->addClass('disabled');
70: $this->template->dangerouslySetHtml('disabled', 'disabled="disabled"');
71: } elseif ($this->readOnly) {
72: $this->addClass('read-only');
73: $this->template->dangerouslySetHtml('disabled', 'readonly="readonly"');
74: }
75:
76: $this->js(true)->checkbox();
77:
78: parent::renderView();
79: }
80:
81: /**
82: * Will return jQuery expression to get checkbox checked state.
83: *
84: * @param bool|string $when
85: * @param JsExpressionable $action
86: *
87: * @return Jquery
88: */
89: public function jsChecked($when = false, $action = null): JsExpressionable
90: {
91: return $this->jsInput($when, $action)->get(0)->checked;
92: }
93: }
94: