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



我正在向模板发送一个表单数组,但是如果我想呈现单个表单元素,我很难弄清楚如何打印开始和结束表单标记。

下面是一个示例,可以让您了解发送给主题函数的结构:

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);

这里是否有合适的方式来呈现每个表单的打开和关闭?

与其在单个表单元素上使用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[]赋值

最新更新