且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Drupal 中创建一个非常简单的表单

更新时间:2023-11-24 10:40:58

使用 Form API自定义模块.您将使用 Form API 构建一个表单并添加一个提交处理程序,该处理程序将表单的重定向更改为您想要的任何内容.最后,您需要创建一种访问表单的方法(通过创建菜单项或通过创建块).

This is pretty easy with the Form API and a custom module. You'll build a form using the Form API and add a submit handler that changes the redirect for the form to whatever you'd like. Finally, you'll need to create a way to access the form (either by creating a menu item or by creating a block).

这是一个实现您想要的表单的示例:您需要仔细阅读表单 API 参考以查看构建表单时的所有选项.它还提供了两种访问表单的方式:

Here's an example that implements a form like you want: you'll want to peruse the Form API reference to see all the options you have when building a form. It also provides two ways to access the form:

  1. 使用 hook_menu() 提供http://example.com/test
  2. 上的表单页面
  3. 使用 hook_block() 提供一个包含表单的块,您可以在块管理页面上添加和移动该表单.

示例代码:

// Form builder. Form ID = function name
function test_form($form_state) {

  $form['postcode'] = array(
    '#type' => 'textfield',
    '#title' => t('Postcode'),
    '#size' => 10,
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Go'),
  );

  return $form;
}

// Form submit handler. Default handler is formid_submit()
function test_form_submit($form, &$form_state) {
  // Redirect the user to http://example.com/test/<Postcode> upon submit
  $form_state['redirect'] = 'test/' . check_plain($form_state['values']['postcode']);
}

// Implementation of hook_menu(): used to create a page for the form
function test_menu() {

  // Create a menu item for http://example.com/test that displays the form
  $items['test'] = array(
    'title' => 'Postcode form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

// Implementation of hook_block(): used to create a movable block for the form
function test_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list': // Show block info on Site Building -> Blocks
      $block['postcode']['info'] = t('Postcode form');
      break;
    case 'view':
      switch ($delta) {
        case 'postcode':
          $block['subject'] = t('Postcode');
          $block['content'] = drupal_get_form('test_form');
          break;
      }
      break;
  }

  return $block;
}

更多信息:

  • Creating modules - a tutorial: Drupal 6.x
  • Form API Quickstart Guide
  • Form API Reference
  • hook_menu() API reference
  • hook_block() API reference
  • Example of hook_block in Drupal 6