Actions
3 years ago
Concerns
3 years ago
Contracts
3 years ago
Exceptions
3 years ago
Facades
4 years ago
LegacyNodes
3 years ago
Checkbox.php
3 years ago
Date.php
3 years ago
Element.php
3 years ago
Email.php
3 years ago
Factory.php
4 years ago
Field.php
3 years ago
File.php
3 years ago
Form.php
3 years ago
Group.php
3 years ago
Hidden.php
3 years ago
Html.php
3 years ago
Option.php
3 years ago
Phone.php
3 years ago
Radio.php
3 years ago
Section.php
3 years ago
Select.php
3 years ago
Text.php
3 years ago
Textarea.php
3 years ago
Types.php
3 years ago
Url.php
3 years ago
Checkbox.php
85 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\FieldsAPI; |
| 4 | |
| 5 | use Give\Framework\Exceptions\Primitives\RuntimeException; |
| 6 | |
| 7 | /** |
| 8 | * @since 2.28.0 |
| 9 | */ |
| 10 | class Checkbox extends Field |
| 11 | { |
| 12 | use Concerns\HasHelpText; |
| 13 | use Concerns\HasLabel; |
| 14 | |
| 15 | const TYPE = 'checkbox'; |
| 16 | |
| 17 | /** |
| 18 | * @var bool whether the checkbox is checked by default |
| 19 | */ |
| 20 | protected $checked = false; |
| 21 | |
| 22 | /** |
| 23 | * @var mixed the value of the checkbox when checked |
| 24 | */ |
| 25 | protected $value; |
| 26 | |
| 27 | /** |
| 28 | * Sets the value the checkbox returns when checked. |
| 29 | * |
| 30 | * The default value is also set because the getDefaultMethod() method is not called during serialization. |
| 31 | * |
| 32 | * @since 2.28.0 |
| 33 | */ |
| 34 | public function value($value): self |
| 35 | { |
| 36 | $this->value = $value; |
| 37 | $this->defaultValue = $this->checked ? $value : null; |
| 38 | |
| 39 | return $this; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * @since 2.28.0 |
| 44 | */ |
| 45 | public function getValue() |
| 46 | { |
| 47 | return $this->value; |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Since the default value needs to reflect the value of the checkbox, this method is not supported. |
| 52 | * |
| 53 | * @since 2.28.0 |
| 54 | */ |
| 55 | public function defaultValue($defaultValue) |
| 56 | { |
| 57 | throw new RuntimeException( |
| 58 | 'Do not set the default value. Instead, set the value and use the checked() method.' |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Sets the checkbox as checked by default |
| 64 | * |
| 65 | * The default value is also set because the getDefaultMethod() method is not called during serialization. |
| 66 | * |
| 67 | * @since 2.28.0 |
| 68 | */ |
| 69 | public function checked(bool $checked = true): self |
| 70 | { |
| 71 | $this->checked = $checked; |
| 72 | $this->defaultValue = $this->checked ? $this->value : null; |
| 73 | |
| 74 | return $this; |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * @since 2.28.0 |
| 79 | */ |
| 80 | public function isChecked(): bool |
| 81 | { |
| 82 | return $this->checked; |
| 83 | } |
| 84 | } |
| 85 |