Merge branch 'MDL-62945-master' of https://github.com/HuongNV13/moodle
[moodle.git] / lib / form / dateselector.php
blobda095b9ac8334bf520dcd7d449abb7ba047dcbc1
1 <?php
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.
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/>.
18 /**
19 * Group of date input element
21 * Contains class for a group of elements used to input a date.
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
28 global $CFG;
29 require_once($CFG->libdir . '/form/group.php');
30 require_once($CFG->libdir . '/formslib.php');
32 /**
33 * Class for a group of elements used to input a date.
35 * Emulates moodle print_date_selector function
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
42 class MoodleQuickForm_date_selector extends MoodleQuickForm_group {
44 /**
45 * Control the fieldnames for form elements.
47 * startyear => int start of range of years that can be selected
48 * stopyear => int last year that can be selected
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}
53 * optional => if true, show a checkbox beside the date to turn it on (or off)
54 * @var array
56 protected $_options = array();
58 /**
59 * @var array These complement separators, they are appended to the resultant HTML.
61 protected $_wrap = array('', '');
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.
68 protected $_usedcreateelement = true;
70 /**
71 * constructor
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
78 public function __construct($elementName = null, $elementLabel = null, $options = array(), $attributes = null) {
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(),
82 'defaulttime' => 0, 'timezone' => 99, 'step' => 1, 'optional' => false);
83 // TODO MDL-52313 Replace with the call to parent::__construct().
84 HTML_QuickForm_element::__construct($elementName, $elementLabel, $attributes);
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;
101 // The YUI2 calendar only supports the gregorian calendar type.
102 if ($calendartype->get_name() === 'gregorian') {
103 form_init_date_js();
108 * Old syntax of class constructor. Deprecated in PHP7.
110 * @deprecated since Moodle 3.1
112 public function MoodleQuickForm_date_selector($elementName = null, $elementLabel = null, $options = array(), $attributes = null) {
113 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
114 self::__construct($elementName, $elementLabel, $options, $attributes);
118 * This will create date group element constisting of day, month and year.
120 * @access private
122 function _createElements() {
123 global $OUTPUT;
125 // Get the calendar type used - see MDL-18375.
126 $calendartype = \core_calendar\type_factory::get_calendar_instance();
128 $this->_elements = array();
130 $dateformat = $calendartype->get_date_order($this->_options['startyear'], $this->_options['stopyear']);
131 // Reverse date element (Day, Month, Year), in RTL mode.
132 if (right_to_left()) {
133 $dateformat = array_reverse($dateformat);
135 foreach ($dateformat as $key => $value) {
136 // E_STRICT creating elements without forms is nasty because it internally uses $this
137 $this->_elements[] = $this->createFormElement('select', $key, get_string($key, 'form'), $value, $this->getAttributes(), true);
139 // The YUI2 calendar only supports the gregorian calendar type so only display the calendar image if this is being used.
140 if ($calendartype->get_name() === 'gregorian') {
141 $image = $OUTPUT->pix_icon('i/calendar', get_string('calendar', 'calendar'), 'moodle');
142 $this->_elements[] = $this->createFormElement('link', 'calendar',
143 null, '#', $image,
144 array('class' => 'visibleifjs'));
146 // If optional we add a checkbox which the user can use to turn if on
147 if ($this->_options['optional']) {
148 $this->_elements[] = $this->createFormElement('checkbox', 'enabled', null, get_string('enable'), $this->getAttributes(), true);
150 foreach ($this->_elements as $element){
151 if (method_exists($element, 'setHiddenLabel')){
152 $element->setHiddenLabel(true);
159 * Called by HTML_QuickForm whenever form event is made on this element
161 * @param string $event Name of event
162 * @param mixed $arg event arguments
163 * @param object $caller calling object
164 * @return bool
166 function onQuickFormEvent($event, $arg, &$caller) {
167 $this->setMoodleForm($caller);
168 switch ($event) {
169 case 'updateValue':
170 // Constant values override both default and submitted ones
171 // default values are overriden by submitted.
172 $value = $this->_findValue($caller->_constantValues);
173 if (null === $value) {
174 // If no boxes were checked, then there is no value in the array
175 // yet we don't want to display default value in this case.
176 if ($caller->isSubmitted()) {
177 $value = $this->_findValue($caller->_submitValues);
178 } else {
179 $value = $this->_findValue($caller->_defaultValues);
182 $requestvalue=$value;
183 if ($value == 0) {
184 $value = time();
186 if (!is_array($value)) {
187 $calendartype = \core_calendar\type_factory::get_calendar_instance();
188 $currentdate = $calendartype->timestamp_to_date_array($value, $this->_options['timezone']);
189 $value = array(
190 'day' => $currentdate['mday'],
191 'month' => $currentdate['mon'],
192 'year' => $currentdate['year']);
193 // If optional, default to off, unless a date was provided.
194 if ($this->_options['optional']) {
195 $value['enabled'] = $requestvalue != 0;
197 } else {
198 $value['enabled'] = isset($value['enabled']);
200 if (null !== $value) {
201 $this->setValue($value);
203 break;
204 case 'createElement':
205 // Optional is an optional param, if its set we need to add a disabledIf rule.
206 // If its empty or not specified then its not an optional dateselector.
207 if (!empty($arg[2]['optional']) && !empty($arg[0])) {
208 // When using the function addElement, rather than createElement, we still
209 // enter this case, making this check necessary.
210 if ($this->_usedcreateelement) {
211 $caller->disabledIf($arg[0] . '[day]', $arg[0] . '[enabled]');
212 $caller->disabledIf($arg[0] . '[month]', $arg[0] . '[enabled]');
213 $caller->disabledIf($arg[0] . '[year]', $arg[0] . '[enabled]');
214 } else {
215 $caller->disabledIf($arg[0], $arg[0] . '[enabled]');
218 return parent::onQuickFormEvent($event, $arg, $caller);
219 break;
220 case 'addElement':
221 $this->_usedcreateelement = false;
222 return parent::onQuickFormEvent($event, $arg, $caller);
223 break;
224 default:
225 return parent::onQuickFormEvent($event, $arg, $caller);
230 * Returns HTML for advchecbox form element.
232 * @return string
234 function toHtml() {
235 include_once('HTML/QuickForm/Renderer/Default.php');
236 $renderer = new HTML_QuickForm_Renderer_Default();
237 $renderer->setElementTemplate('{element}');
238 parent::accept($renderer);
240 $html = $this->_wrap[0];
241 if ($this->_usedcreateelement) {
242 $html .= html_writer::tag('span', $renderer->toHtml(), array('class' => 'fdate_selector'));
243 } else {
244 $html .= $renderer->toHtml();
246 $html .= $this->_wrap[1];
248 return $html;
252 * Accepts a renderer
254 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
255 * @param bool $required Whether a group is required
256 * @param string $error An error message associated with a group
258 function accept(&$renderer, $required = false, $error = null) {
259 $renderer->renderElement($this, $required, $error);
263 * Output a timestamp. Give it the name of the group.
265 * @param array $submitValues values submitted.
266 * @param bool $assoc specifies if returned array is associative
267 * @return array
269 function exportValue(&$submitValues, $assoc = false) {
270 $valuearray = array();
271 foreach ($this->_elements as $element){
272 $thisexport = $element->exportValue($submitValues[$this->getName()], true);
273 if ($thisexport!=null){
274 $valuearray += $thisexport;
277 if (count($valuearray) && isset($valuearray['year'])) {
278 if($this->_options['optional']) {
279 // If checkbox is on, the value is zero, so go no further
280 if(empty($valuearray['enabled'])) {
281 return $this->_prepareValue(0, $assoc);
284 // Get the calendar type used - see MDL-18375.
285 $calendartype = \core_calendar\type_factory::get_calendar_instance();
286 $gregoriandate = $calendartype->convert_to_gregorian($valuearray['year'], $valuearray['month'], $valuearray['day']);
287 $value = make_timestamp($gregoriandate['year'],
288 $gregoriandate['month'],
289 $gregoriandate['day'],
290 0, 0, 0,
291 $this->_options['timezone'],
292 true);
294 return $this->_prepareValue($value, $assoc);
295 } else {
296 return null;