1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Carbon_Fields\Field; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Number field class. |
7
|
|
|
*/ |
8
|
|
|
class Number_Field extends Field { |
9
|
|
|
|
10
|
|
|
protected $default_min = 1; |
11
|
|
|
protected $default_max = 2147483647; |
12
|
|
|
protected $default_step = 1; |
13
|
|
|
|
14
|
|
|
protected $min = 1; |
15
|
|
|
protected $max = 2147483647; |
16
|
|
|
protected $step = 1; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Underscore template of this field. |
20
|
|
|
*/ |
21
|
|
|
function template() { |
|
|
|
|
22
|
|
|
?> |
23
|
|
|
<input id="{{{ id }}}" type="number" name="{{{ name }}}" value="{{ value }}" max="{{ max }}" min="{{ min }}" step="{{ step }}" pattern="[0-9]*" class="regular-text" /> |
24
|
|
|
<?php |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
function to_json( $load ) { |
|
|
|
|
28
|
|
|
$field_data = parent::to_json( $load ); |
29
|
|
|
|
30
|
|
|
$field_data = array_merge( $field_data, array( |
31
|
|
|
'min' => is_numeric( $this->min ) ? $this->min : $this->default_min, |
32
|
|
|
'max' => is_numeric( $this->max ) ? $this->max : $this->default_max, |
33
|
|
|
'step' => is_numeric( $this->step ) ? $this->step : $this->default_step, |
34
|
|
|
) ); |
35
|
|
|
|
36
|
|
|
return $field_data; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
function save() { |
|
|
|
|
40
|
|
|
$name = $this->get_name(); |
41
|
|
|
$value = $this->get_value(); |
42
|
|
|
$min = $this->min; |
43
|
|
|
$max = $this->max; |
44
|
|
|
$step = $this->step; |
45
|
|
|
|
46
|
|
|
// Set the value for the field |
47
|
|
|
$this->set_name( $name ); |
48
|
|
|
|
49
|
|
|
$field_value = ''; |
50
|
|
|
if ( isset( $value ) && $value !== '' && is_numeric( $value ) ) { |
51
|
|
|
$value = floatval( $value ); |
52
|
|
|
|
53
|
|
|
$is_valid_min = $min <= $value; |
54
|
|
|
$is_valid_max = $value <= $max; |
55
|
|
|
|
56
|
|
|
// Base Formula "value = min + n * step" where "n" should be integer |
57
|
|
|
$test_for_step_validation = ( $value - $min ) / $step; |
58
|
|
|
$is_valid_step = $test_for_step_validation === floor( $test_for_step_validation ); |
59
|
|
|
|
60
|
|
|
if ( $value !== '' && $is_valid_min && $is_valid_max && $is_valid_step ) { |
|
|
|
|
61
|
|
|
$field_value = $value; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$this->set_value( $field_value ); |
66
|
|
|
|
67
|
|
|
parent::save(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
function set_max( $max ) { |
|
|
|
|
71
|
|
|
$this->max = $max; |
72
|
|
|
|
73
|
|
|
return $this; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
function set_min( $min ) { |
|
|
|
|
77
|
|
|
$this->min = $min; |
78
|
|
|
|
79
|
|
|
return $this; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
function set_step( $step ) { |
|
|
|
|
83
|
|
|
$this->step = $step; |
84
|
|
|
|
85
|
|
|
return $this; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.