主题化表单的最灵活的方式,就是为表单或者表单元素使用一个特定的主题函数。这里涉及到了两个步骤。首先,Drupal需要知道我们的模块将实现哪些主题函数。这可以通过hook_theme()(详细请参看第8章)来完成。下面是我们模块的hook_theme()的一个快速实现,它主要说的是“我们的模块提供了两个主题函数,无须额外参数就可以调用它们”:
/**
* Implementation of hook_theme().
*/
function formexample_theme() {
return array(
'formexample_nameform' => array(
'arguments' => array(),
),
'formexample_alternate_nameform' => array(
'arguments' => array(),
)
);
}
在默认情况下,Drupal会查找名为“‘theme_’+表单ID的名字”的主题函数。在我们的例子中,Drupal将在主题注册表中查找theme_formexample_nameform条目,由于我们在formexample_theme()中定义了它,所以Drupal能够找到它。将会调用下面的主题函数,而它的输出与Drupal的默认主题化完全一样:
function theme_formexample_nameform($form) {
$output = drupal_render($form);
return $output;
}
拥有我们自己的主题函数的好处是,我们可以按照我们的意愿对变量$output进行解析、混合、添加等操作。我们可以很快的将一个特定元素放在表单的最前面。例如在下面的例子中,我们把颜色字段集放在了最前面。
function theme_formexample_nameform($form) {
// Always put the the color selection at the top.
$output = drupal_render($form['color']);
// Then add the rest of the form.
$output .= drupal_render($form);
return $output;
}
老葛的Drupal培训班 Think in Drupal