Projet

Général

Profil

Paste
Télécharger (26,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / date / date_elements.inc @ db9ffd17

1
<?php
2
/**
3
 * @file
4
 * Date forms and form themes and validation.
5
 *
6
 * All code used in form editing and processing is in this file,
7
 * included only during form editing.
8
 */
9

    
10
/**
11
 * Private implementation of hook_widget().
12
 *
13
 * The widget builds out a complex date element in the following way:
14
 *
15
 * - A field is pulled out of the database which is comprised of one or
16
 *   more collections of start/end dates.
17
 *
18
 * - The dates in this field are all converted from the UTC values stored
19
 *   in the database back to the local time. This is done in #process
20
 *   to avoid making this change to dates that are not being processed,
21
 *   like those hidden with #access.
22
 *
23
 * - If values are empty, the field settings rules are used to determine
24
 *   if the default_values should be empty, now, the same, or use strtotime.
25
 *
26
 * - Each start/end combination is created using the date_combo element type
27
 *   defined by the date module. If the timezone is date-specific, a
28
 *   timezone selector is added to the first combo element.
29
 *
30
 * - The date combo element creates two individual date elements, one each
31
 *   for the start and end field, using the appropriate individual Date API
32
 *   date elements, like selects, textfields, or popups.
33
 *
34
 * - In the individual element validation, the data supplied by the user is
35
 *   used to update the individual date values.
36
 *
37
 * - In the combo date validation, the timezone is updated, if necessary,
38
 *   then the user input date values are used with that timezone to create
39
 *   date objects, which are used update combo date timezone and offset values.
40
 *
41
 * - In the field's submission processing, the new date values, which are in
42
 *   the local timezone, are converted back to their UTC values and stored.
43
 *
44
 */
45
function date_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $base) {
46

    
47
  $element = $base;
48
  $field_name = $field['field_name'];
49
  $entity_type = $instance['entity_type'];
50

    
51
  // If this is a new entity, populate the field with the right default values.
52
  // This happens early so even fields later hidden with #access get those values.
53
  // We should only add default values to new entities, to avoid over-writing
54
  // a value that has already been set. This means we can't just check to see
55
  // if $items is empty, because it might have been set that way on purpose.
56
  // @see date_field_widget_properties_alter() where we flagged if this is a new entity.
57

    
58
  // We check !isset($items[$delta]['value']) because entity translation may create
59
  // a new translation entity for an existing entity and we don't want to clobber
60
  // values that were already set in that case.
61
  // @see http://drupal.org/node/1478848.
62

    
63
  $is_default = FALSE;
64
  if (!empty($instance['widget']['is_new']) && !isset($items[$delta]['value'])) {
65
    $items = date_default_value($field, $instance, $langcode);
66
    $is_default = TRUE;
67
  }
68

    
69
  // @TODO Repeating dates should probably be made into their own field type and completely separated out.
70
  // That will have to wait for a new branch since it may break other things, including other modules
71
  // that have an expectation of what the date field types are.
72

    
73
  // Since repeating dates cannot use the default Add more button, we have to handle our own behaviors here.
74
  // Return only the first multiple value for repeating dates, then clean up the 'Add more' bits in #after_build.
75
  // The repeating values will be re-generated when the repeat widget form is validated.
76
  // At this point we can't tell if this form element is going to be hidden by #access, and we're going to
77
  // lose all but the first value by doing this, so store the original values in case we need to replace them later.
78
  if (!empty($field['settings']['repeat'])) {
79
    if ($delta == 0) {
80
      $form['#after_build'][] = 'date_repeat_after_build';
81
      $form_state['storage']['repeat_fields'][$field_name] = array_merge($form['#parents'], array($field_name));
82
      $form_state['storage']['date_items'][$field_name][$langcode] = $items;
83
    }
84
    else {
85
      return;
86
    }
87
  }
88

    
89
  module_load_include('inc', 'date_api', 'date_api_elements');
90
  $timezone = date_get_timezone($field['settings']['tz_handling'], isset($items[0]['timezone']) ? $items[0]['timezone'] : date_default_timezone());
91

    
92
  // TODO see if there's a way to keep the timezone element from ever being
93
  // nested as array('timezone' => 'timezone' => value)). After struggling
94
  // with this a while, I can find no way to get it displayed in the form
95
  // correctly and get it to use the timezone element without ending up
96
  // with nesting.
97
  if (is_array($timezone)) {
98
    $timezone = $timezone['timezone'];
99
  }
100

    
101
  $element += array(
102
    '#type' => 'date_combo',
103
    '#theme_wrappers' => array('date_combo'),
104
    '#weight' => $delta,
105
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
106
    '#date_timezone' => $timezone,
107
    '#element_validate' => array('date_combo_validate'),
108
    '#date_is_default' => $is_default,
109

    
110
    // Store the original values, for use with disabled and hidden fields.
111
    '#date_items' => isset($items[$delta]) ? $items[$delta] : '',
112
  );
113

    
114
  $element['#title'] = $instance['label'];
115

    
116
  if ($field['settings']['tz_handling'] == 'date') {
117
    $element['timezone'] = array(
118
      '#type' => 'date_timezone',
119
      '#theme_wrappers' => array('date_timezone'),
120
      '#delta' => $delta,
121
      '#default_value' => $timezone,
122
      '#weight' => $instance['widget']['weight'] + 1,
123
      '#attributes' => array('class' => array('date-no-float')),
124
      '#date_label_position' => $instance['widget']['settings']['label_position'],
125
      );
126
  }
127

    
128
  return $element;
129
}
130

    
131
/**
132
 * Create local date object.
133
 *
134
 * Create a date object set to local time from the field and
135
 * widget settings and item values. Default values for new entities
136
 * are set by the default value callback, so don't need to be accounted for here.
137
 */
138
function date_local_date($item, $timezone, $field, $instance, $part = 'value') {
139

    
140
  $value = $item[$part];
141

    
142
  // If the value is empty, don't try to create a date object because it will
143
  // end up being the current day.
144
  if (empty($value)) {
145
    return NULL;
146
  }
147

    
148
  // @TODO Figure out how to replace date_fuzzy_datetime() function.
149
  // Special case for ISO dates to create a valid date object for formatting.
150
  // Is this still needed?
151
  /*
152
  if ($field['type'] == DATE_ISO) {
153
    $value = date_fuzzy_datetime($value);
154
  }
155
  else {
156
    $db_timezone = date_get_timezone_db($field['settings']['tz_handling']);
157
    $value = date_convert($value, $field['type'], DATE_DATETIME, $db_timezone);
158
  }
159
  */
160

    
161
  $date = new DateObject($value, date_get_timezone_db($field['settings']['tz_handling']));
162
  $date->limitGranularity($field['settings']['granularity']);
163
  if (empty($date)) {
164
    return NULL;
165
  }
166
  date_timezone_set($date, timezone_open($timezone));
167

    
168
  return $date;
169
}
170

    
171
/**
172
 * The callback for setting a default value for an empty date field.
173
 */
174
function date_default_value($field, $instance, $langcode) {
175
  $item = array();
176
  $db_format = date_type_format($field['type']);
177
  $date = date_default_value_part($item, $field, $instance, $langcode, 'value');
178
  $item[0]['value'] = is_object($date) ? date_format($date, $db_format) : '';
179
  if (!empty($field['settings']['todate'])) {
180
    $date = date_default_value_part($item, $field, $instance, $langcode, 'value2');
181
    $item[0]['value2'] = is_object($date) ? date_format($date, $db_format) : '';
182
  }
183

    
184
  // Make sure the default value has the same construct as a loaded field value
185
  // to avoid errors if the default value is used on a hidden element.
186
  $item[0]['timezone'] = date_get_timezone($field['settings']['tz_handling']);
187
  $item[0]['timezone_db'] = date_get_timezone_db($field['settings']['tz_handling']);
188
  $item[0]['date_type'] = $field['type'];
189
  if (!isset($item[0]['value2'])) {
190
    $item[0]['value2'] = $item[0]['value'];
191
  }
192
  return $item;
193
}
194

    
195
/**
196
 * Helper function for the date default value callback to set
197
 * either 'value' or 'value2' to its default value.
198
 */
199
function date_default_value_part($item, $field, $instance, $langcode, $part = 'value') {
200
  $timezone = date_get_timezone($field['settings']['tz_handling']);
201
  $timezone_db = date_get_timezone_db($field['settings']['tz_handling']);
202
  $date = NULL;
203
  if ($part == 'value') {
204
    $default_value = $instance['settings']['default_value'];
205
    $default_value_code = $instance['settings']['default_value_code'];
206
  }
207
  else {
208
    $default_value = $instance['settings']['default_value2'];
209
    $default_value_code = $instance['settings']['default_value_code2'];
210
  }
211
  if (empty($default_value) || $default_value == 'blank') {
212
    return NULL;
213
  }
214
  elseif ($default_value == 'strtotime' && !empty($default_value_code)) {
215
    $date = new DateObject($default_value_code, date_default_timezone());
216
  }
217
  elseif ($part == 'value2' && $default_value == 'same') {
218
    if ($instance['settings']['default_value'] == 'blank' || empty($item[0]['value'])) {
219
      return NULL;
220
    }
221
    else {
222
      // The date stored in 'value' has already been switched to the db timezone.
223
      $date = new DateObject($item[0]['value'], $timezone_db, DATE_FORMAT_DATETIME);
224
    }
225
  }
226
  // Special case for 'now' when using dates with no timezone,
227
  // make sure 'now' isn't adjusted to UTC value of 'now' .
228
  elseif ($field['settings']['tz_handling'] == 'none') {
229
    $date = date_now();
230
  }
231
  else {
232
    $date = date_now($timezone);
233
  }
234
  // The default value needs to be in the database timezone.
235
  date_timezone_set($date, timezone_open($timezone_db));
236
  $date->limitGranularity($field['settings']['granularity']);
237
  return $date;
238
}
239

    
240
/**
241
 * Process an individual date element.
242
 */
243
function date_combo_element_process($element, &$form_state, $form) {
244
    
245
  if (date_hidden_element($element)) {
246
    // A hidden value for a new entity that had its end date set to blank
247
    // will not get processed later to populate the end date, so set it here.
248
    if (isset($element['#value']['value2']) && empty($element['#value']['value2'])) {
249
      $element['#value']['value2'] = $element['#value']['value'];
250
    }
251
    return $element;
252
  }
253

    
254
  $field_name = $element['#field_name'];
255
  $delta = $element['#delta'];
256
  $bundle = $element['#bundle'];
257
  $entity_type = $element['#entity_type'];
258
  $langcode = $element['#language'];
259
  $date_is_default = $element['#date_is_default'];
260

    
261
  $field = field_widget_field($element, $form_state);
262
  $instance = field_widget_instance($element, $form_state);
263

    
264
  // Figure out how many items are in the form, including new ones added by ajax.
265
  $field_state = field_form_get_state($element['#field_parents'], $field_name, $element['#language'], $form_state);
266
  $items_count = $field_state['items_count'];
267

    
268
  $columns = $element['#columns'];
269
  if (isset($columns['rrule'])) {
270
    unset($columns['rrule']);
271
  }
272
  $from_field = 'value';
273
  $to_field = 'value2';
274
  $tz_field = 'timezone';
275
  $offset_field = 'offset';
276
  $offset_field2 = 'offset2';
277

    
278
  // Convert UTC dates to their local values in DATETIME format,
279
  // and adjust the default values as specified in the field settings.
280

    
281
  // It would seem to make sense to do this conversion when the data
282
  // is loaded instead of when the form is created, but the loaded
283
  // field data is cached and we can't cache dates that have been converted
284
  // to the timezone of an individual user, so we cache the UTC values
285
  // instead and do our conversion to local dates in the form and
286
  // in the formatters.
287
  $process = date_process_values($field, $instance);
288
  foreach ($process as $processed) {
289
    if (!isset($element['#default_value'][$processed])) {
290
      $element['#default_value'][$processed] = '';
291
    }
292
    $date = date_local_date($element['#default_value'], $element['#date_timezone'], $field, $instance, $processed);
293
    $element['#default_value'][$processed] = is_object($date) ? date_format($date, DATE_FORMAT_DATETIME) : '';
294
  }
295

    
296
  // Blank out the end date for optional end dates that match the start date,
297
  // except when this is a new node that has default values that should be honored.
298
  if (!$date_is_default && $field['settings']['todate'] != 'required'
299
  && !empty($element['#default_value'][$to_field])
300
  && $element['#default_value'][$to_field] == $element['#default_value'][$from_field]) {
301
    unset($element['#default_value'][$to_field]);
302
  }
303

    
304
  $show_todate = !empty($form_state['values']['show_todate']) || !empty($element['#default_value'][$to_field]) || $field['settings']['todate'] == 'required';
305
  $element['show_todate'] = array(
306
    '#title' => t('Show End Date'),
307
    '#type' => 'checkbox',
308
    '#default_value' => $show_todate,
309
    '#weight' => -20,
310
    '#access' => $field['settings']['todate'] == 'optional',
311
    '#prefix' => '<div class="date-float">',
312
    '#suffix' => '</div>',
313
  );
314

    
315
  $parents = $element['#parents'];
316
  $first_parent = array_shift($parents);
317
  $show_id = $first_parent . '[' . implode('][', $parents) . '][show_todate]';
318

    
319
  $element[$from_field] = array(
320
    '#field'         => $field,
321
    '#instance'      => $instance,
322
    '#weight'        => $instance['widget']['weight'],
323
    '#required'      => ($element['#required'] && $delta == 0) ? 1 : 0,
324
    '#default_value' => isset($element['#default_value'][$from_field]) ? $element['#default_value'][$from_field] : '',
325
    '#delta'         => $delta,
326
    '#date_timezone' => $element['#date_timezone'],
327
    '#date_format'      => date_limit_format(date_input_format($element, $field, $instance), $field['settings']['granularity']),
328
    '#date_text_parts'  => (array) $instance['widget']['settings']['text_parts'],
329
    '#date_increment'   => $instance['widget']['settings']['increment'],
330
    '#date_year_range'  => $instance['widget']['settings']['year_range'],
331
    '#date_label_position' => $instance['widget']['settings']['label_position'],
332
    );
333

    
334
  $description =  !empty($element['#description']) ? t($element['#description']) : '';
335
  unset($element['#description']);
336

    
337
  // Give this element the right type, using a Date API
338
  // or a Date Popup element type.
339
  $element[$from_field]['#attributes'] = array('class' => array('date-clear'));
340
  $element[$from_field]['#wrapper_attributes'] = array('class' => array());
341
  $element[$from_field]['#wrapper_attributes']['class'][] = 'date-no-float';
342

    
343
  switch ($instance['widget']['type']) {
344
    case 'date_select':
345
      $element[$from_field]['#type'] = 'date_select';
346
      $element[$from_field]['#theme_wrappers'] = array('date_select');
347
      $element['#attached']['js'][] = drupal_get_path('module', 'date') . '/date.js';
348
      $element[$from_field]['#ajax'] = !empty($element['#ajax']) ? $element['#ajax'] : FALSE;
349
      break;
350
    case 'date_popup':
351
      $element[$from_field]['#type'] = 'date_popup';
352
      $element[$from_field]['#theme_wrappers'] = array('date_popup');
353
      $element[$from_field]['#ajax'] = !empty($element['#ajax']) ? $element['#ajax'] : FALSE;
354
      break;
355
    default:
356
      $element[$from_field]['#type'] = 'date_text';
357
      $element[$from_field]['#theme_wrappers'] = array('date_text');
358
      $element[$from_field]['#ajax'] = !empty($element['#ajax']) ? $element['#ajax'] : FALSE;
359
      break;
360
  }
361

    
362
  // If this field uses the 'End', add matching element
363
  // for the 'End' date, and adapt titles to make it clear which
364
  // is the 'Start' and which is the 'End' .
365

    
366
  if (!empty($field['settings']['todate'])) {
367
    $element[$to_field] = $element[$from_field];
368
    $element[$from_field]['#title_display'] = 'none';
369
    $element[$to_field]['#title'] = t('to:');
370
    $element[$from_field]['#wrapper_attributes']['class'][] = 'start-date-wrapper';
371
    $element[$to_field]['#wrapper_attributes']['class'][] = 'end-date-wrapper';
372
    $element[$to_field]['#default_value'] = isset($element['#default_value'][$to_field]) ? $element['#default_value'][$to_field] : '';
373
    $element[$to_field]['#required'] = ($element[$from_field]['#required'] && $field['settings']['todate'] == 'required');
374
    $element[$to_field]['#weight'] += .2;
375
    $element[$to_field]['#prefix'] = '';
376
    // Users with JS enabled will never see initially blank values for the end
377
    // date (see Drupal.date.EndDateHandler()), so hide the message for them.
378
    $description .= '<span class="js-hide"> ' . t("Empty 'End date' values will use the 'Start date' values.") . '</span>';
379
    $element['#fieldset_description'] = $description;
380
    if ($field['settings']['todate'] == 'optional') {
381
      $element[$to_field]['#states'] = array(
382
        'visible' => array(
383
          'input[name="' . $show_id . '"]' => array('checked' => TRUE),
384
      ));
385
    }
386
  }
387
  else {
388
    $element[$from_field]['#description'] = $description;
389
  }
390

    
391
  // Create label for error messages that make sense in multiple values
392
  // and when the title field is left blank.
393
  if ($field['cardinality'] <> 1 && empty($field['settings']['repeat'])) {
394
    $element[$from_field]['#date_title'] = t('@field_name Start date value #@delta', array('@field_name' => $instance['label'], '@delta' => $delta + 1));
395
    if (!empty($field['settings']['todate'])) {
396
      $element[$to_field]['#date_title'] = t('@field_name End date value #@delta', array('@field_name' => $instance['label'], '@delta' => $delta + 1));
397
    }
398
  }
399
  elseif (!empty($field['settings']['todate'])) {
400
    $element[$from_field]['#date_title'] = t('@field_name Start date', array('@field_name' => $instance['label']));
401
    $element[$to_field]['#date_title'] = t('@field_name End date', array('@field_name' => $instance['label']));
402
  }
403
  else {
404
    $element[$from_field]['#date_title'] = t('@field_name', array('@field_name' => $instance['label']));
405
  }
406

    
407
  $context = array(
408
   'field' => $field,
409
   'instance' => $instance,
410
   'form' => $form,
411
  );
412
  drupal_alter('date_combo_process', $element, $form_state, $context);
413

    
414
  return $element;
415
}
416

    
417
function date_element_empty($element, &$form_state) {
418
  $item = array();
419
  $item['value'] = NULL;
420
  $item['value2']   = NULL;
421
  $item['timezone']   = NULL;
422
  $item['offset'] = NULL;
423
  $item['offset2'] = NULL;
424
  $item['rrule'] = NULL;
425
  form_set_value($element, $item, $form_state);
426
  return $item;
427
}
428

    
429
/**
430
 * Validate and update a combo element.
431
 * Don't try this if there were errors before reaching this point.
432
 */
433
function date_combo_validate($element, &$form_state) {
434

    
435
  // Disabled and hidden elements won't have any input and don't need validation,
436
  // we just need to re-save the original values, from before they were processed into
437
  // widget arrays and timezone-adjusted.
438
  if (date_hidden_element($element) || !empty($element['#disabled'])) {
439
    form_set_value($element, $element['#date_items'], $form_state);
440
    return;
441
  }
442

    
443
  $field_name = $element['#field_name'];
444
  $delta = $element['#delta'];
445
  $langcode = $element['#language'];
446

    
447
  $form_values = drupal_array_get_nested_value($form_state['values'], $element['#field_parents']);
448
  $form_input = drupal_array_get_nested_value($form_state['input'], $element['#field_parents']);
449

    
450
  // If the whole field is empty and that's OK, stop now.
451
  if (empty($form_input[$field_name]) && !$element['#required']) {
452
    return;
453
  }
454

    
455
  $item = drupal_array_get_nested_value($form_state['values'], $element['#parents']);
456
  $posted = drupal_array_get_nested_value($form_state['input'], $element['#parents']);
457

    
458
  $field = field_widget_field($element, $form_state);
459
  $instance = field_widget_instance($element, $form_state);
460

    
461
  $context = array(
462
    'field' => $field,
463
    'instance' => $instance,
464
    'item' => $item,
465
  );
466

    
467
  drupal_alter('date_combo_pre_validate', $element, $form_state, $context);
468

    
469
  $from_field = 'value';
470
  $to_field = 'value2';
471
  $tz_field = 'timezone';
472
  $offset_field = 'offset';
473
  $offset_field2 = 'offset2';
474

    
475
  // Check for empty 'Start date', which could either be an empty
476
  // value or an array of empty values, depending on the widget.
477
  $empty = TRUE;
478
  if (!empty($item[$from_field])) {
479
    if (!is_array($item[$from_field])) {
480
      $empty = FALSE;
481
    }
482
    else {
483
      foreach ($item[$from_field] as $key => $value) {
484
        if (!empty($value)) {
485
          $empty = FALSE;
486
          break;
487
        }
488
      }
489
    }
490
  }
491

    
492
  // An 'End' date without a 'Start' date is a validation error.
493
  if ($empty && !empty($item[$to_field])) {
494
    if (!is_array($item[$to_field])) {
495
      form_error($element, t("A 'Start date' date is required if an 'end date' is supplied for field %field #%delta.", array('%delta' => $field['cardinality'] ? intval($delta + 1) : '', '%field' => $instance['label'])));
496
      $empty = FALSE;
497
    }
498
    else {
499
      foreach ($item[$to_field] as $key => $value) {
500
        if (!empty($value)) {
501
          form_error($element, t("A 'Start date' date is required if an 'End date' is supplied for field %field #%delta.", array('%delta' => $field['cardinality'] ? intval($delta + 1) : '', '%field' => $instance['label'])));
502
          $empty = FALSE;
503
          break;
504
        }
505
      }
506
    }
507
  }
508

    
509
  // If the user chose the option to not show the end date, just swap in the
510
  // start date as that value so the start and end dates are the same.
511
  if ($field['settings']['todate'] == 'optional' && empty($item['show_todate'])) {
512
    $item[$to_field] = $item[$from_field];
513
    $posted[$to_field] = $posted[$from_field];
514
  }
515

    
516
  if ($empty) {
517
    $item = date_element_empty($element, $form_state);
518
    if (!$element['#required']) {
519
      return;
520
    }
521
  }
522
  // Don't look for further errors if errors are already flagged
523
  // because otherwise we'll show errors on the nested elements
524
  // more than once.
525
  elseif (!form_get_errors()) {
526

    
527
    $timezone = !empty($item[$tz_field]) ? $item[$tz_field] : $element['#date_timezone'];
528
    $timezone_db = date_get_timezone_db($field['settings']['tz_handling']);
529
    $element[$from_field]['#date_timezone'] = $timezone;
530
    $from_date = date_input_date($field, $instance, $element[$from_field], $posted[$from_field]);
531

    
532
    if (!empty($field['settings']['todate'])) {
533
      $element[$to_field]['#date_timezone'] = $timezone;
534
      $to_date = date_input_date($field, $instance, $element[$to_field], $posted[$to_field]);
535
    }
536
    else {
537
      $to_date = $from_date;
538
    }
539

    
540
    // Neither the start date nor the end date should be empty at this point
541
    // unless they held values that couldn't be evaluated.
542

    
543
    if (!$instance['required'] && (!date_is_date($from_date) || !date_is_date($to_date))) {
544
      $item = date_element_empty($element, $form_state);
545
      $errors[] = t('The dates are invalid.');
546
    }
547
    elseif (!empty($field['settings']['todate']) && $from_date > $to_date) {
548
      form_set_value($element[$to_field], $to_date, $form_state);
549
      $errors[] = t('The End date must be greater than the Start date.');
550
    }
551
    else {
552
      // Convert input dates back to their UTC values and re-format to ISO
553
      // or UNIX instead of the DATETIME format used in element processing.
554
      $item[$tz_field] = $timezone;
555

    
556
      // Update the context for changes in the $item, and allow other modules to
557
      // alter the computed local dates.
558
      $context['item'] = $item;
559
      // We can only pass two additional values to drupal_alter, so $element
560
      // needs to be included in $context.
561
      $context['element'] = $element;
562
      drupal_alter('date_combo_validate_date_start', $from_date, $form_state, $context);
563
      drupal_alter('date_combo_validate_date_end', $to_date, $form_state, $context);
564

    
565
      $item[$offset_field] = date_offset_get($from_date);
566

    
567
      $test_from = date_format($from_date, 'r');
568
      $test_to = date_format($to_date, 'r');
569

    
570
      $item[$offset_field2] = date_offset_get($to_date);
571
      date_timezone_set($from_date, timezone_open($timezone_db));
572
      date_timezone_set($to_date, timezone_open($timezone_db));
573
      $item[$from_field] = date_format($from_date, date_type_format($field['type']));
574
      $item[$to_field] = date_format($to_date, date_type_format($field['type']));
575
      if (isset($form_values[$field_name]['rrule'])) {
576
        $item['rrule'] = $form_values[$field['field_name']]['rrule'];
577
      }
578

    
579
      // If the db timezone is not the same as the display timezone
580
      // and we are using a date with time granularity,
581
      // test a roundtrip back to the original timezone to catch
582
      // invalid dates, like 2AM on the day that spring daylight savings
583
      // time begins in the US.
584
      $granularity = date_format_order($element[$from_field]['#date_format']);
585
      if ($timezone != $timezone_db && date_has_time($granularity)) {
586
        date_timezone_set($from_date, timezone_open($timezone));
587
        date_timezone_set($to_date, timezone_open($timezone));
588

    
589
        if ($test_from != date_format($from_date, 'r')) {
590
          $errors[] = t('The Start date is invalid.');
591
        }
592
        if ($test_to != date_format($to_date, 'r')) {
593
          $errors[] = t('The End date is invalid.');
594
        }
595
      }
596
      if (empty($errors)) {
597
        form_set_value($element, $item, $form_state);
598
      }
599
    }
600
  }
601
  if (!empty($errors)) {
602
    if ($field['cardinality']) {
603
      form_error($element, t('There are errors in @field_name value #@delta:', array('@field_name' => $instance['label'], '@delta' => $delta + 1)) . theme('item_list', array('items' => $errors)));
604
    }
605
    else {
606
      form_error($element, t('There are errors in @field_name:', array('@field_name' => $instance['label'])) . theme('item_list', array('items' => $errors)));
607
    }
608
  }
609
}
610

    
611
/**
612
 * Determine the input format for this element.
613
 */
614
function date_input_format($element, $field, $instance) {
615
  if (!empty($instance['widget']['settings']['input_format_custom'])) {
616
    return $instance['widget']['settings']['input_format_custom'];
617
  }
618
  elseif (!empty($instance['widget']['settings']['input_format']) && $instance['widget']['settings']['input_format'] != 'site-wide') {
619
    return $instance['widget']['settings']['input_format'];
620
  }
621
  return variable_get('date_format_short', 'm/d/Y - H:i');
622
}
623

    
624

    
625
/**
626
 * Implements hook_date_select_pre_validate_alter().
627
 */
628
function date_date_select_pre_validate_alter(&$element, &$form_state, &$input) {
629
  date_empty_end_date($element, $form_state, $input);
630
}
631

    
632
/**
633
 * Implements hook_date_text_pre_validate_alter().
634
 */
635
function date_date_text_pre_validate_alter(&$element, &$form_state, &$input) {
636
  date_empty_end_date($element, $form_state, $input);
637
}
638

    
639
/**
640
 * Implements hook_date_popup_pre_validate_alter().
641
 */
642
function date_date_popup_pre_validate_alter(&$element, &$form_state, &$input) {
643
  date_empty_end_date($element, $form_state, $input);
644
}
645

    
646
/**
647
 * Helper function to clear out end date when not being used.
648
 */
649
function date_empty_end_date(&$element, &$form_state, &$input) {
650
  // If this is the end date and the option to show an end date has not been selected,
651
  // empty the end date to surpress validation errors and stop further processing.
652
  $parents = $element['#parents'];
653
  $parent = array_pop($parents);
654
  if ($parent == 'value2') {
655
    $parent_values = drupal_array_get_nested_value($form_state['values'], $parents);
656
    if (isset($parent_values['show_todate']) && $parent_values['show_todate'] != 1) {
657
      $input = array();
658
      form_set_value($element, NULL, $form_state);
659
    }
660
  }
661
}