weekly release 4.1dev
[moodle.git] / lib / form / dateselector.php
CommitLineData
4a0e2e63 1<?php
6c1fd304
RT
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
25fe66b0 16
6c1fd304
RT
17
18/**
19 * Group of date input element
20 *
21 * Contains class for a group of elements used to input a date.
22 *
23 * @package core_form
24 * @copyright 2007 Jamie Pratt <me@jamiep.org>
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
25fe66b0 27
da6f8763 28global $CFG;
25fe66b0 29require_once($CFG->libdir . '/form/group.php');
30require_once($CFG->libdir . '/formslib.php');
da6f8763 31
32/**
33 * Class for a group of elements used to input a date.
7f42315c 34 *
35 * Emulates moodle print_date_selector function
36 *
6c1fd304
RT
37 * @package core_form
38 * @category form
39 * @copyright 2007 Jamie Pratt <me@jamiep.org>
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
da6f8763 41 */
2f00e1b2
MN
42class MoodleQuickForm_date_selector extends MoodleQuickForm_group {
43
da6f8763 44 /**
2f00e1b2 45 * Control the fieldnames for form elements.
6dd59aab 46 *
6c1fd304
RT
47 * startyear => int start of range of years that can be selected
48 * stopyear => int last year that can be selected
fa70f635
RT
49 * timezone => int|float|string (optional) timezone modifier used for edge case only.
50 * If not specified, then date is caclulated based on current user timezone.
51 * Note: dst will be calculated for string timezones only
52 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
6c1fd304
RT
53 * optional => if true, show a checkbox beside the date to turn it on (or off)
54 * @var array
55 */
1d43da02 56 protected $_options = array();
da6f8763 57
34f9862e
MN
58 /**
59 * @var array These complement separators, they are appended to the resultant HTML.
60 */
25fe66b0 61 protected $_wrap = array('', '');
da6f8763 62
34f9862e
MN
63 /**
64 * @var null|bool Keeps track of whether the date selector was initialised using createElement
65 * or addElement. If true, createElement was used signifying the element has been
66 * added to a group - see MDL-39187.
67 */
68 protected $_usedcreateelement = true;
69
6c1fd304
RT
70 /**
71 * constructor
72 *
73 * @param string $elementName Element's name
74 * @param mixed $elementLabel Label(s) for an element
75 * @param array $options Options to control the element's display
76 * @param mixed $attributes Either a typical HTML attribute string or an associative array
77 */
1a0df553 78 public function __construct($elementName = null, $elementLabel = null, $options = array(), $attributes = null) {
1d43da02
MN
79 // Get the calendar type used - see MDL-18375.
80 $calendartype = \core_calendar\type_factory::get_calendar_instance();
81 $this->_options = array('startyear' => $calendartype->get_min_year(), 'stopyear' => $calendartype->get_max_year(),
223419d9 82 'defaulttime' => 0, 'timezone' => 99, 'step' => 1, 'optional' => false);
32fada5c 83 // TODO MDL-52313 Replace with the call to parent::__construct().
1a0df553 84 HTML_QuickForm_element::__construct($elementName, $elementLabel, $attributes);
da6f8763 85 $this->_persistantFreeze = true;
86 $this->_appendName = true;
87 $this->_type = 'date_selector';
88 // set the options, do not bother setting bogus ones
89 if (is_array($options)) {
90 foreach ($options as $name => $value) {
91 if (isset($this->_options[$name])) {
92 if (is_array($value) && is_array($this->_options[$name])) {
93 $this->_options[$name] = @array_merge($this->_options[$name], $value);
94 } else {
95 $this->_options[$name] = $value;
96 }
97 }
98 }
99 }
100 }
101
1a0df553
MG
102 /**
103 * Old syntax of class constructor. Deprecated in PHP7.
104 *
105 * @deprecated since Moodle 3.1
106 */
107 public function MoodleQuickForm_date_selector($elementName = null, $elementLabel = null, $options = array(), $attributes = null) {
108 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
109 self::__construct($elementName, $elementLabel, $options, $attributes);
110 }
111
6c1fd304
RT
112 /**
113 * This will create date group element constisting of day, month and year.
114 *
115 * @access private
116 */
2f00e1b2
MN
117 function _createElements() {
118 global $OUTPUT;
f40df210 119
2f00e1b2 120 // Get the calendar type used - see MDL-18375.
6eafa4dd 121 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2f00e1b2
MN
122
123 $this->_elements = array();
73412d96 124
1d43da02 125 $dateformat = $calendartype->get_date_order($this->_options['startyear'], $this->_options['stopyear']);
bb13339a
NK
126 // Reverse date element (Day, Month, Year), in RTL mode.
127 if (right_to_left()) {
128 $dateformat = array_reverse($dateformat);
129 }
73412d96
AG
130 foreach ($dateformat as $key => $value) {
131 // E_STRICT creating elements without forms is nasty because it internally uses $this
721e2def 132 $this->_elements[] = $this->createFormElement('select', $key, get_string($key, 'form'), $value, $this->getAttributes(), true);
73412d96 133 }
29cb1e83 134 // The YUI2 calendar only supports the gregorian calendar type so only display the calendar image if this is being used.
6b7d0d3e 135 if ($calendartype->get_name() === 'gregorian') {
83e9f0ad 136 $image = $OUTPUT->pix_icon('i/calendar', get_string('calendar', 'calendar'), 'moodle');
721e2def 137 $this->_elements[] = $this->createFormElement('link', 'calendar',
91de0ed8 138 null, '#', $image);
29cb1e83 139 }
46e648b6 140 // If optional we add a checkbox which the user can use to turn if on
29cb1e83 141 if ($this->_options['optional']) {
721e2def 142 $this->_elements[] = $this->createFormElement('checkbox', 'enabled', null, get_string('enable'), $this->getAttributes(), true);
de312b53 143 }
44875d78 144 foreach ($this->_elements as $element){
145 if (method_exists($element, 'setHiddenLabel')){
146 $element->setHiddenLabel(true);
147 }
148 }
da6f8763 149
150 }
151
11f260f4 152 /**
153 * Called by HTML_QuickForm whenever form event is made on this element
58b7d48f 154 *
6c1fd304
RT
155 * @param string $event Name of event
156 * @param mixed $arg event arguments
157 * @param object $caller calling object
158 * @return bool
11f260f4 159 */
2f00e1b2 160 function onQuickFormEvent($event, $arg, &$caller) {
721e2def 161 $this->setMoodleForm($caller);
11f260f4 162 switch ($event) {
163 case 'updateValue':
deed22ea
MN
164 // Constant values override both default and submitted ones
165 // default values are overriden by submitted.
11f260f4 166 $value = $this->_findValue($caller->_constantValues);
167 if (null === $value) {
deed22ea
MN
168 // If no boxes were checked, then there is no value in the array
169 // yet we don't want to display default value in this case.
5079271b 170 if ($caller->isSubmitted() && !$caller->is_new_repeat($this->getName())) {
11f260f4 171 $value = $this->_findValue($caller->_submitValues);
172 } else {
173 $value = $this->_findValue($caller->_defaultValues);
174 }
175 }
176 $requestvalue=$value;
177 if ($value == 0) {
178 $value = time();
179 }
180 if (!is_array($value)) {
deed22ea
MN
181 $calendartype = \core_calendar\type_factory::get_calendar_instance();
182 $currentdate = $calendartype->timestamp_to_date_array($value, $this->_options['timezone']);
11f260f4 183 $value = array(
184 'day' => $currentdate['mday'],
185 'month' => $currentdate['mon'],
186 'year' => $currentdate['year']);
deed22ea
MN
187 // If optional, default to off, unless a date was provided.
188 if ($this->_options['optional']) {
25fe66b0 189 $value['enabled'] = $requestvalue != 0;
11f260f4 190 }
191 } else {
25fe66b0 192 $value['enabled'] = isset($value['enabled']);
11f260f4 193 }
deed22ea 194 if (null !== $value) {
11f260f4 195 $this->setValue($value);
196 }
197 break;
198 case 'createElement':
fec617de
SH
199 // Optional is an optional param, if its set we need to add a disabledIf rule.
200 // If its empty or not specified then its not an optional dateselector.
201 if (!empty($arg[2]['optional']) && !empty($arg[0])) {
e019dccc
MN
202 // When using the function addElement, rather than createElement, we still
203 // enter this case, making this check necessary.
204 if ($this->_usedcreateelement) {
205 $caller->disabledIf($arg[0] . '[day]', $arg[0] . '[enabled]');
206 $caller->disabledIf($arg[0] . '[month]', $arg[0] . '[enabled]');
207 $caller->disabledIf($arg[0] . '[year]', $arg[0] . '[enabled]');
208 } else {
209 $caller->disabledIf($arg[0], $arg[0] . '[enabled]');
210 }
11f260f4 211 }
212 return parent::onQuickFormEvent($event, $arg, $caller);
213 break;
34f9862e
MN
214 case 'addElement':
215 $this->_usedcreateelement = false;
216 return parent::onQuickFormEvent($event, $arg, $caller);
217 break;
11f260f4 218 default:
219 return parent::onQuickFormEvent($event, $arg, $caller);
da6f8763 220 }
6c1fd304 221 }
da6f8763 222
6c1fd304
RT
223 /**
224 * Returns HTML for advchecbox form element.
225 *
226 * @return string
227 */
2f00e1b2 228 function toHtml() {
da6f8763 229 include_once('HTML/QuickForm/Renderer/Default.php');
bd69b9db 230 $renderer = new HTML_QuickForm_Renderer_Default();
da6f8763 231 $renderer->setElementTemplate('{element}');
232 parent::accept($renderer);
34f9862e
MN
233
234 $html = $this->_wrap[0];
235 if ($this->_usedcreateelement) {
236 $html .= html_writer::tag('span', $renderer->toHtml(), array('class' => 'fdate_selector'));
237 } else {
238 $html .= $renderer->toHtml();
239 }
240 $html .= $this->_wrap[1];
241
242 return $html;
da6f8763 243 }
244
6c1fd304
RT
245 /**
246 * Accepts a renderer
247 *
248 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
249 * @param bool $required Whether a group is required
250 * @param string $error An error message associated with a group
251 */
2f00e1b2 252 function accept(&$renderer, $required = false, $error = null) {
57876874 253 form_init_date_js();
da6f8763 254 $renderer->renderElement($this, $required, $error);
255 }
256
57876874
MG
257 /**
258 * Export for template
259 *
260 * @param renderer_base $output
261 * @return array|stdClass
262 */
263 public function export_for_template(renderer_base $output) {
264 form_init_date_js();
265 return parent::export_for_template($output);
266 }
267
da6f8763 268 /**
269 * Output a timestamp. Give it the name of the group.
270 *
6c1fd304
RT
271 * @param array $submitValues values submitted.
272 * @param bool $assoc specifies if returned array is associative
da6f8763 273 * @return array
274 */
2f00e1b2 275 function exportValue(&$submitValues, $assoc = false) {
57cf1be2 276 $valuearray = array();
277 foreach ($this->_elements as $element){
278 $thisexport = $element->exportValue($submitValues[$this->getName()], true);
279 if ($thisexport!=null){
280 $valuearray += $thisexport;
281 }
282 }
b4eb5f02 283 if (count($valuearray) && isset($valuearray['year'])) {
de312b53 284 if($this->_options['optional']) {
11f260f4 285 // If checkbox is on, the value is zero, so go no further
25fe66b0 286 if(empty($valuearray['enabled'])) {
80180e0f 287 return $this->_prepareValue(0, $assoc);
de312b53 288 }
289 }
2f00e1b2 290 // Get the calendar type used - see MDL-18375.
6eafa4dd 291 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2f00e1b2 292 $gregoriandate = $calendartype->convert_to_gregorian($valuearray['year'], $valuearray['month'], $valuearray['day']);
80180e0f 293 $value = make_timestamp($gregoriandate['year'],
2f00e1b2
MN
294 $gregoriandate['month'],
295 $gregoriandate['day'],
296 0, 0, 0,
297 $this->_options['timezone'],
298 true);
57cf1be2 299
80180e0f 300 return $this->_prepareValue($value, $assoc);
57cf1be2 301 } else {
302 return null;
303 }
da6f8763 304 }
da6f8763 305}