在自定义模块中,我希望在hook_menu中定义一个页面,该页面显示特定内容类型的添加表单,并对表单进行一些修改。
到目前为止,它正在工作,甚至保存新节点,但只使用我在代码中设置的默认值,即它没有拾取用户在表单中键入的任何内容。我检查了$form_state['input']
包含输入的值,但$form_state['values']
没有,因此新节点保存错误。
以下是相关代码:
function mymodule_menu() {
return array(
'admin/content/myadd/%' => array(
'title' => 'my custom add page',
'page callback' => 'mymodule_node_add',
'page arguments' => array(3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
),
);
}
function mymodule_node_add() {
module_load_include('inc', 'node', 'node.pages');
//I'm doing a print here instead of returning because I'm calling this page
//in an AJAX popup, so I don't want the whole page to output, only the form.
print render(drupal_get_form('mymodule_node_add_form'));
}
function mymodule_node_add_form($form, &$form_state) {
if (!isset($form_state['node']) {
global $user;
$node = (object) array(
'uid' => $user->uid,
'type' => 'mycontenttype',
'language' => LANGUAGE_NONE,
);
//this is setting a default value
$node->myfield = array(LANGUAGE_NONE => array(array('value' => arg(3))));
$form_state['build_info']['args'] = array($node);
$form = drupal_build_form('mycontenttype_node_form', $form_state);
$form['actions']['submit']['#submit'][0] = 'mymodule_node_add_form_submit';
//there's a lot more customization of the form here, like adding fields, etc.
}
return $form;
}
function mymodule_node_add_form_submit($form, &$form_state) {
//here's where $form_state['input'] is correct but $form_state['values'] isn't.
$node = node_form_submit_build_node($form, $form_state);
node_save($node);
$form_state['values']['nid'] = $node->nid;
$form_state['nid'] = $node->nid;
$form_state['redirect'] = 'some/other/page';
}
那么,我在这里做错了吗?我应该担心表格ID是错误的吗? (我的表单的ID是mymodule_node_add_form
,但实际表单可能会输出mycontenttype_node_form
),这会影响我吗?
答案 0 :(得分:0)
您想要hook_form_alter()
(请参阅api.drupal.org)。我会尝试使用现有的内容类型的表单,只需使用hook_form_alter()更改它。我还会尝试将其作为标准的非AJAX页面使用,这样您就可以获得dpm()和其他调试技术的所有优点。当你把它固定下来,然后修改它以利用AJAX技术。
mymodule_form_alter(&$form, &$form_state, $form_id) {
// use this with your devel module turned on to verify
// your $form_id and contents of all forms that load on a given page
dpm($form);
// once you verify your $form_id, you can begin accessing your form and altering it
switch( $form_id ) {
case 'my_target_form_id' :
// this part is just pseudocode, I haven't memorized the $form structure,
// you can get it from your dpm().
if( $form['node']->type == 'my_target_content_type' ) {
$form['actions']['submit']['#submit'][0] = 'mymodule_node_add_form_submit';
}
break;
}
}