0

在自定义模块中,我希望在 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),这会影响我吗?

4

1 回答 1

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;
  }
}
于 2013-09-06T23:55:59.630 回答