drupal将Date表单元素月日年的顺序改造为年月日的方法

本文实例讲述了drupal将Date表单元素月日年的顺序改造为年月日的方法。分享给大家供大家参考。具体实现方法如下:

我们在表单元素中,很多时候都会使用date这样的元素,但是,你会发现,这个元素由3个select组成,他们的顺序为月,日,年,这是不符合中国的习惯的。

我在帮人指导建站的时候,就遇到了这样的问题,但是找不到答案。我判断,可以通过theme层搞定这个问题,这样就去找了对应的theme函数。这个问题在网上好像是找不到答案的,我google了多次,但是都找不到,也有人遇到了同样的问题,但是都是绕道而行。

我决定尝试着解决这样的问题,因为我相信,一定存在一个方法,将月日年的顺序调整为年月日。先看系统生成的默认元素里面的markup。然后就去找对应的主题函数,这样就找到了theme_date。

具体代码如下:

function theme_date($element) {
return theme('form_element', $element, '<div class="container-inline">'. $element['#children'] .'</div>');
}

container-inline就是这里生成。但是3个子元素的顺序不是这里决定的。我的第一个想法是,覆写这个函数,print_r($element['#children']),这样就可以到定这个顺序问题了。

不过我很想知道,核心代码中,哪部分决定了3个子元素的顺序,这样,就找到了expand_date($element)。其具体代码如下:

function expand_date($element) {
// Default to current date
if (empty($element['#value'])) {
$element['#value'] = array('day' => format_date(time(), 'custom', 'j'),
'month' => format_date(time(), 'custom', 'n'),
'year' => format_date(time(), 'custom', 'Y'));
}

$element['#tree'] = TRUE;

// Determine the order of day, month, year in the site's chosen date format.此处决定日期格式:
$format = variable_get('date_format_short', 'm/d/Y - H:i');
$sort = array();
$sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
$sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
$sort['year'] = strpos($format, 'Y');
asort($sort);
$order = array_keys($sort);

// Output multi-selector for date.
foreach ($order as $type) {
switch ($type) {
case 'day':
$options = drupal_map_assoc(range(1, 31));
break;
case 'month':
$options = drupal_map_assoc(range(1, 12), 'map_month');
break;
case 'year':
$options = drupal_map_assoc(range(1900, 2050));
break;
}
$parents = $element['#parents'];
$parents[] = $type;
$element[$type] = array(
'#type' => 'select',
'#value' => $element['#value'][$type],
'#attributes' => $element['#attributes'],
'#options' => $options,
);
}

return $element;
}

注意代码注释说明的部分,3个子元素的顺序,是由日期格式决定的,我猜测,调整日期格式,就可以改变3个子元素的顺序,我尝试着将日期格式都改为了年月日:导航到admin/settings/date-time,将3中长,中,短的日期格式都调整为自定义格式,Y/m/d(D) H:i。

这样,date元素中的顺序,就从“月,日,年”调整为了“年,月,日”。

希望本文所述对大家的drupal二次开发有所帮助。