Drupal 7: Hook_menu 和 form的用法

回复
头像
Mia2014
帖子: 1805
注册时间: 周三 12月 25, 2013 8:24 pm

Drupal 7: Hook_menu 和 form的用法

帖子 Mia2014 » 周五 2月 28, 2014 6:00 pm

先附例子代码:

function mymodule_menu() {

$items = array();
$items['node/1/%/%'] = array(
'title' => t('Search Result'),
'description' => t('Search Result'),
'page callback' => 'drupal_get_form',
'page arguments' => array('test_form',2,3),
'access callback' => TRUE,
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
);

return $items;
}

function test_form($form, &$form_state, $arg0, $arg1) {
$form = array();

$form['carrental_service'] = array(
'#type' => 'select',
'#title' => t('Argument'),
'#options' => array(
0 => $arg0,
1 => $arg1,
),
'#required' => TRUE,
'#weight' => 1,
'#default_value' => '',
'#description' => t(''),
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#weight' => 2,
);

return $form;
}

运行时,如果使用链接:http://domainname/node/1/value1/value2,函数test_form()里的参数$arg0=value1, $arg1=value2。
我总结几个注意的地方:
如果不使用form,在'page callback' => 'drupal_get_form', 直接写调用的函数test_form()。test_form()就不能使用参数$form, &$form_state,就不能使用$form。另外,'page arguments' => array('test_form',2,3), 写为'page arguments' => array(2,3), 。在test_form()要用return返回一个字符串。

如果使用form, 就是上面的代码。'page arguments' 要先用'test_form'指定要调用的函数,而在 'page callback' 写'drupal_get_form'。

其他的请参看:
function hook_menu
https://api.drupal.org/api/drupal/modul ... ook_menu/7
Form API Reference
https://api.drupal.org/api/drupal/devel ... nce.html/7

回复