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

   2015-08-02 0
核心提示:这篇文章主要为大家介绍了drupal将Date表单元素月日年的顺序改造为年月日的方法,是很多drupal用户在进行二次开发的时候都会遇到的问题,需要的朋友可以参考下

本文实例讲述了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二次开发有所帮助。

 
标签: Drupal
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

点击排行