【发布时间】:2010-08-16 12:29:56
【问题描述】:
我需要做的就是有一个执行此操作的表单:
- 用户在文本框中输入邮政编码
- 提交后,用户被重定向到 mysite.com/[user postcode]
就是这样!我知道验证等也是可取的,但我现在只需要让它工作。我不介意它是经过硬编码还是使用 Drupal 表单 API(实际上我更喜欢前者!)。
我知道这很简单,但不幸的是,我来自前端背景,并且对这类事情有一些了解:(
干杯!
【问题讨论】:
我需要做的就是有一个执行此操作的表单:
就是这样!我知道验证等也是可取的,但我现在只需要让它工作。我不介意它是经过硬编码还是使用 Drupal 表单 API(实际上我更喜欢前者!)。
我知道这很简单,但不幸的是,我来自前端背景,并且对这类事情有一些了解:(
干杯!
【问题讨论】:
使用Form API 和a custom module 非常简单。您将使用 Form API 构建一个表单并添加一个提交处理程序,该处理程序将表单的重定向更改为您想要的任何内容。最后,您需要创建一种访问表单的方法(通过创建菜单项或创建块)。
这是一个实现您想要的表单的示例:您需要仔细阅读表单 API 参考以查看构建表单时拥有的所有选项。它还提供了两种访问表单的方式:
hook_menu() 为http://example.com/test 的表单提供一个页面
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;
}
更多信息:
【讨论】:
Drupal Form API - 非常简单,作为开发人员最终需要学习它。不妨跳进去通过 API 来做,因为它不是太难,你正在尝试做的事情。
【讨论】:
一旦掌握了窍门,在 Drupal 中创建表单就相当容易了。我建议阅读以下链接。 http://drupal.org/node/751826 它很好地概述了如何创建表单。
在 _submit 钩子中,您可以通过设置 $form_state['redirect'] 重定向到相应的页面。
这当然是假设您已经掌握了创建自定义模块的窍门。如果您需要更多信息,请转至here。
【讨论】:
drupal_goto():它会在其他提交处理程序之前立即停止处理表单,这些提交处理程序可能已经附加到您的表单之后。 $form_state['redirect'] 是处理提交重定向的首选方式,因为它不会中断表单工作流并允许其他提交处理程序完成。