在自定义模块Drupal 7中添加/编辑表单?

时间:2017-04-22 12:12:18

标签: drupal drupal-7

您好我制作自定义表单以在自定义模块中添加内容。我创建另一个表单来编辑自定义节点。我想在一个表单中合并两个表单以进行添加和编辑。

function example_add_form($form, &$form_state) {


  $form['name']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
  );

  $form['name']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
  );


  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Create Order',
  );

  return $form;
}

function example_add_form_submit($form, &$form_state) {


  $node = new stdClass();
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->title = $form_state['values']['title'];
  $node->body[LANGUAGE_NONE][0]['value'] = $form_state['values']['description'];
  node_save($node);

}

这是我的编辑表格,这是我的编辑表格,这是我的编辑表格 这是我的编辑表格 这是我的编辑表格 这是我的编辑表格

function example_edit_form($form, &$form_state, $nid) {

  global $node;
  $node = node_load($nid);

  $form['title'] = array(
    '#title' => 'Title',
    '#type' => 'textfield',
    '#default_value' => $node->title,
  );

  $form['name']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $node->body[LANGUAGE_NONE][0]['value'],
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Update Order',
  );

  return $form;
}

1 个答案:

答案 0 :(得分:0)

尝试这样,它可能对你有用

在条件

中传递参数nid
// $nid = ''; //by default NULL
// $nid = YOUR_NODE_ID; pass nid when you edit the node

function example_add_form($form, &$form_state, $nid) {

  global $node;
  if(!empty($nid)){
    $node = node_load($nid);
    $body = $node->body[LANGUAGE_NONE][0]['value'];
  }

  // Create Hidden field    
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid, // pass node id in form data
  );

  $form['name']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
    '#default_value' => isset($node->title) ? $node->title : NULL;
  );


  $form['name']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => isset($body) ? $body : NULL;
  );


  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Create Order',
  );

  return $form;
}

function example_add_form_submit($form, &$form_state) {

  // check if nid value is empty then create a node otherwise update it
  if(empty($form_state['values']['nid']){
  $node = new stdClass();
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->title = $form_state['values']['title'];
  $node->body[LANGUAGE_NONE][0]['value'] = $form_state['values']['description'];
  node_save($node);
  }else{
    // update node data
  }

}

另外一件事,如果您不想创建nid隐藏字段,那么您可以通过这种方式直接获取表单提交中的nid值

$form_state['build_info']['args']; is an array containing at index 0 the value of argument nid