如何为自定义表单实施“添加其他项目”?


9

我正在编写一个模块,该模块基本上是一种在两个端点之间创建关系的形式。

我希望用户能够一次创建多个关系。我想添加一个按钮,上面写着“添加其他项目”,就像您在设置中选择无限制时字段的显示方式一样。

有没有办法我也可以自定义表单呢?

Answers:


12

一种方法是在for函数中设置表单字段/字段集。创建一个单独的函数以通过例如提交按钮回调来增加值,并在增加后重建表单。

for($x=1; $x<=$variabletoincrement; $x++){
(insert form fields/field sets )
}

这是来自form_example_tutorial_9的代码,该代码显示有关如何创建动态字段的信息。这些信息比我的解释要彻底得多:

http://api.drupal.org/api/examples/form_example!form_example_tutorial.inc/function/form_example_tutorial_9_add_name/7

http://api.drupal.org/api/examples/form_example%21form_example_tutorial.inc/function/form_example_tutorial_9/7


8

有一个简单而有效的代码示例:

function MYMODULE_MYFORM($form, &$form_state) {

  // #tree will ensure the HTML elements get named distinctively.
  // Not just name=[name] but name=[container][123][name].
  $form['#tree'] = TRUE;

  if (empty($form_state['number_names'])) {
    $form_state['number_names'] = 1;
  }

  for ($i = 1; $i <= $form_state['number_names']; $i++) {

    $form['container'][$i] = array(
      '#type' => 'container',
    );
    $form['container'][$i]['name'] = array(
      '#type' => 'textfield',
      '#attributes' =>array('placeholder' => t('Name')),
      '#size' => 20,
      '#required' => TRUE,
    );
  }

  $form['add_item'] = array(
    '#type' => 'submit',
    '#value' => t('Add another name'),
    '#submit' => array('MYMODULE_MYFORM_add_item'),
  );

  if ($form_state['number_names'] > 1) {

    $form['remove_item'] = array(
      '#type' => 'submit',
      '#value' => t('Remove latest name'),
      '#submit' => array('MYMODULE_MYFORM_remove_item'),
      // Since we are removing a name, don't validate until later.
      '#limit_validation_errors' => array(),
    );
  }

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

  return $form;
}

function MYMODULE_MYFORM_add_item($form, &$form_state) {

  // All we need is to increase the number used in our for loop above ...
  $form_state['number_names']++;
  // ... and rebuild our form.
  $form_state['rebuild'] = TRUE;
}

function MYMODULE_MYFORM_remove_item($form, &$form_state) {

  // Just the other way around until only one item is left ...
  if ($form_state['number_names'] > 1) {
    $form_state['number_names']--;
  }
  // ... and form rebuild again.
  $form_state['rebuild'] = TRUE;
}

Drupal 8

查看示例模块的示例AjaxAddMore.php(单击小的“查看源代码”链接)。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.