Drupal使用或者开发过程中最常用到的Hooks(钩子)莫过于hook_form_alter,你所常见的Drupal网站中的内容创建,联系表单,Menu菜单,用户注册等等都会用到表单的钩子。
Drupal Form Hooks
hook_form_alter 中的hook直接替换为你的模块名称。
代码如下 | 复制代码 |
/** * Implements hook_form_alter(). */ function custom_form_alter(&$form, &$form_state, $form_id) { switch($form_id) { case ‘user_profile_form’: //doing something break; } } |
hook_form_FORM_ID_alter 是 hook_form_alter的一个变种,直接对某一个具体的表单进行修改
代码如下 | 复制代码 |
/** * Implements hook_form_FORM_ID_alter(). */ function custom_form_user_profile_form_alter(&$form, &$form_state) { if ($form['#user_category'] == ‘settings’) { if (variable_get(‘configurable_timezones’, 1)) { system_user_timezone($form, $form_state); } return $form; } } |
通过以上2个Hooks就可以轻松给Drupal 添加自定义的表单元素。
每一个form都可以自定义theme前段元素,render的elements 都会通过variables传递给主题。
代码如下 | 复制代码 |
/** * Implements hook_theme(). */ function custom_theme() { return array( ‘user_profile_form’ => array( ‘render element’ => ‘form’, ), ); } |
自定义form的element样式。
代码如下 | 复制代码 |
function theme_user_profile_form($variables) { $form = $variables['form']; $output = drupal_render($form['info']); $header = array(t(‘Factor’), t(‘Weight’)); $output .= drupal_render_children($form); |
通过 hook_preprocess_FORM_ID 在theme form element之前修改$variables
代码如下 | 复制代码 |
function custom_preprocess_user_profile_form(&$variables) { if ($variables['form’][‘actions]) { //change the button name } // add new variable to theme form } |
自定义form的html元素,可以将form的theme定义一个template,注意这样会降低drupal的性能,但是换来的好处是可以自定义html。
代码如下 | 复制代码 |
/** * Implements hook_theme(). */ function lixiphp_theme($existing, $type, $theme, $path){ return array( ‘user_profile_form’ => array( ‘render element’=>’form’, ‘template’ =>’templates/form/user-profile’, ), ); } |
创建user-profile.tpl.php文件在templates/form目录下。
代码如下 | 复制代码 |
<?php print drupal_render($form['form_id']); print drupal_render($form['form_build_id']); print drupal_render($form['form_token']); ?> <li class=“rows”> <?php print drupal_render($form['actions']); ?> </li> |
本文讲究的form自定义方法实用于Drupal6,Drupal7和Drupal8。