在模板中呈现多个表单,包括呈现表单元素

时间:2013-05-23 04:35:43

标签: drupal drupal-7

我正在向模板发送一系列表单,但如果我想渲染单个表单元素,我很难弄清楚如何打开和关闭表单标签。

这是一个示例,让您了解发送到主题函数的结构:

function mymodule_page_callback() {
  ...
  $i = 0;
  foreach ($widgets as $widget) {
    $forms[] = drupal_get_form('my_renderable_form_' . $i, $widget);
    $i++;
  }
  return theme('my_theme_function', array('forms' => $forms));
}

在我的模板中,我正在构建一个每行1个表单的表。这是我能让它发挥作用的唯一方法:

$header = array('field 1', 'field 2', '');
foreach ($variables['forms'] as $form) {
  $row = array(
    drupal_render($form['field1']),
    drupal_render($form['field2']),
    // Manually set the closing form tag
    drupal_render($form['submit']) . drupal_render_children($form) . '</form>'
  );
  // Now drupal_render($form) to get the opening/closing form tags
  // and stuff it at the beginning of the 1st column.
  // This has to be done last so the rest of the form doesn't render with it.
  $row[0] = str_replace('</form>', '', drupal_render($form)) . $row[0];
  $rows[] = $row;
}
print theme('table', array('header' => $header, 'rows' => $rows);

是否有正确的方法来渲染每个表单的打开和关闭?

1 个答案:

答案 0 :(得分:-2)

不要在单个表单元素上使用drupal_render,而是在整个表单上使用render

$header = array('field 1', 'field 2', '');
foreach ($variables['forms'] as $form) {
  $rows[] = array(array('data' => render($form), 'colspan' => 3));
}
print theme('table', array('header' => $header, 'rows' => $rows);

您应该考虑使用tableselect Form API元素。

编辑:更新了theme_table文档中指定的$ rows []赋值。