时间:2024-09-27 来源:网络 人气:
Drupal 7 模块开发:如何增加自定义表单
在Drupal 7中,模块开发是构建强大、灵活网站的关键。其中一个常见的需求是在模块中增加自定义表单。本文将详细介绍如何在Drupal 7模块中增加表单,包括表单的创建、验证、提交以及与数据库的交互。
```html
在开始之前,请确保您已经安装了Drupal 7开发环境,并且熟悉基本的Drupal模块开发流程。
创建一个新的模块。在Drupal的根目录下,创建一个名为 `my_custom_form` 的文件夹,并在该文件夹中创建以下文件:
- `my_custom_form.info`:模块信息文件。
- `my_custom_form.module`:模块代码文件。
在 `my_custom_form.info` 文件中,添加以下内容:
```plaintext
name = My Custom Form
type = Module
description = Adds a custom form to the Drupal 7 site.
core_version_requirement = ^7.0
package = Custom
dependencies[] = core
在 `my_custom_form.module` 文件中,添加以下内容:
```php
getType() == 'custom_form') {
$variables['content']['my_custom_form'] = array(
'type' => 'container',
'attributes' => array('id' => 'my-custom-form'),
);
$variables['content']['my_custom_form']['form'] = drupal_get_form('my_custom_form_form');
Returns a form structure.
function my_custom_form_form() {
$form = array();
$form['name'] = array(
'type' => 'textfield',
'title' => t('Name'),
'required' => TRUE,
);
$form['email'] = array(
'type' => 'email',
'title' => t('Email'),
'required' => TRUE,
);
$form['submit'] = array(
'type' => 'submit',
'value' => t('Submit'),
);
return $form;
Form submission handler.
function my_custom_form_form_submit($form, &$form_state) {
// Process the form submission here.
drupal_set_message(t('Thank you for your submission.'));
在 `my_custom_form.module` 文件中,注册表单:
```php
Implements hook_menu().
function my_custom_form_menu() {
$items = array();
$items['custom-form'] = array(
'title' => t('Custom Form'),
'page callback' => 'drupal_get_form',
'page arguments' => array('my_custom_form_form'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM,
);
return $items;
为了使表单能够被提交,我们需要创建一个节点类型。在 `my_custom_form.info` 文件中,添加以下内容:
```plaintext
node_types[] = custom_form
在 `my_custom_form.module` 文件中,添加以下内容:
```php
Implements hook_node_info().
function my_custom_form_node_info() {
$info = array();
$info['custom_form'] = array(
'name' => t('Custom Form'),
'type' => t('Content'),
'description' => t('Custom form content type.'),
'base_table' => 'custom_form',
'has_title' => TRUE,
'title_field' => 'title',
'has_body' => TRUE,
'body_field' => 'body',
'has_publishing_options' => TRUE,
'revisions' => TRUE,
'status_field' => 'status',
'register_node_type' => TRUE,
);
return $info;
现在,您可以通过以下步骤测试模块:
1. 在Drupal后台,启用 `my_custom_form` 模块。
2. 访问 `/custom-form` 路径,您应该看到一个包含表单的页面。
3. 填写表单并提交,您应该看到一条消息提示“Thank you for your submission.”。