1 <?php
2
3 /**
4 * Single boolean checkbox.
5 *
6 * @package Fieldmanager_Field
7 */
8 class Fieldmanager_Checkbox extends Fieldmanager_Field {
9
10 /**
11 * @var mixed
12 * Value when checked
13 */
14 public $checked_value = TRUE;
15
16 /**
17 * @var mixed
18 * Value when unchecked
19 */
20 public $unchecked_value = FALSE;
21
22 /**
23 * @var boolean
24 * Override save_empty default for this element type
25 */
26 public $save_empty = True;
27
28 /**
29 * @var boolean
30 * Override inline_label
31 */
32 public $inline_label = True;
33
34 /**
35 * @var boolean
36 * Override label_after_element
37 */
38 public $label_after_element = True;
39
40 /**
41 * Form element implementation for checkboxes
42 * @param mixed $value
43 * @return string HTML
44 */
45 public function form_element( $value = NULL ) {
46 return sprintf(
47 '<input type="hidden" name="%1$s" value="%6$s" /><input class="fm-element" type="checkbox" name="%1$s" value="%2$s" %3$s %4$s id="%5$s" />',
48 esc_attr( $this->get_form_name() ),
49 esc_attr( (string) $this->checked_value ),
50 $this->get_element_attributes(),
51 ( $value == $this->checked_value ) ? 'checked="checked"' : "",
52 esc_attr( $this->get_element_id() ),
53 $this->unchecked_value
54 );
55 }
56
57 /**
58 * Override presave function to swap in unchecked_value if needed
59 * @param mixed $value
60 * @return mixed proper value
61 */
62 public function presave( $value = NULL, $current_value = array() ) {
63 if ( $value == $this->checked_value || $value === $this->unchecked_value ) {
64 return $value;
65 } elseif ( empty( $value ) ) {
66 return $this->unchecked_value;
67 }
68 else {
69 $this->_unauthorized_access( __( 'Saved a checkbox with a value that was not one of the options', 'fieldmanager' ) );
70 }
71 }
72 }
73