drupal7 form模板复写方法

给form制作一个template

从官方的drupal api document中可得到form有#theme这个参数,它可以指定form使用一个模板来用于form的基本布局,#theme的值必须是通过hook_theme声明的key。一般情况下,即使不去声明#theme,#theme也会有一个与本form同名的默认值,所以只需要用hook_theme声明一个与form name一样的key就可以。

mymodule.module:

function mymodule_form(){
  // ...
  return $form;
}

function mymodule_theme() {
    return array(
        // theme name与form ID一样。这是由于每个form[#theme]都有一个等于form ID的默认值。
        'mymodule_form' => array(
            'render element' => 'form',
            'template' => 'mymodule-form', // 对应文件名mymodule-form.tpl.php
        ),
    );
}

mymodule-form.tpl.php (其它HTML代码随意):

<?php $form = $variables['form'];?>

<?php echo drupal_render($form['name']); // 'name' form element ?>

<?php echo drupal_render_children($form); // print other all form element ?>

 

可以使用hook_form_alter修改form的内容,前提是得到form ID(drupal中所有form都会有一个form ID,一般与创建form的函数名相同)
http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7

以下方法可以输出所有form的form ID,得到form ID才可以对form进行单独操作,建议加到theme下的template.php中,命名为mytheme_form_alter (mytheme要改为当前theme的名字)

function mytheme_form_alter(&$form, &$form_state, $form_id) {
  $print = '<pre>' . print_r($form, TRUE) . '</pre>';
  if (module_exists('devel')) {
    dsm($form_id); // print form ID to messages
  }
  else {
    drupal_set_message($form_id); // print form ID to messages
  }
  if (module_exists('devel')) {
    dsm($form); // pretty print array using Krumo to messages
  }
  else {
    drupal_set_message($print);  // print array to messages
  }
}

 

posted @ 2013-09-20 17:40  猫之良品  阅读(2350)  评论(0编辑  收藏  举报