【问题标题】:Drupal Form API - Using foreach loops to build formsDrupal Form API - 使用 foreach 循环构建表单
【发布时间】:2011-06-23 15:31:53
【问题描述】:

我正在构建一个 Drupal 模块,以使用管理表单将图标绑定到特定页面。放置在某个目录中的每个图像都需要输出,旁边有一个选择框,显示所有主链接标题。

我使用foreach 循环构建了表单,但是当我在_submit 函数中使用dpm($form); 检查输出时,每个图像页面元素的#value 始终等于为最后一个图像设置的值。

这是我的代码:

function titleicon_admin_settings() {


  $settings = variable_get('titleicon_settings', $default);

  //build an array of primary link titles
  $primary_links_items = menu_primary_links();
  foreach ($primary_links_items as $item) {
    $title = $item['attributes']['title'];
    $href = $item['href'];
    $titles[$href] = $title;
  }

  //build array of icons
  $directory = file_directory_path() . '/icons';
  $mask = '(jpg|jpeg|gif|png|JPG|JPEG|GIF|PNG)';
  $icons = file_scan_directory($directory, $mask);



  foreach ($icons as $icon) {
    $name = $icon->name;
    $path = base_path() . $icon->filename;
    $html = '<img src="' . $path . '" width="50" height="50" />';
    $default_value = $settings[$name]['page'];

    $form[$name] = array(
      '#type' => 'fieldset',
      '#title' => $name,
    );

    $form[$name]['path_to_icon'] = array(
      '#type' => 'value',
      '#value' => $path, 
    );

    $form[$name]['icon'] = array(
      '#type' => 'markup',
      '#value' => $html, 
    );

    $form[$name]['page'] = array(
      '#type' => 'select',
      '#title' => t('Show icon on page'),
      '#default_value' => $default_value,
      '#description' => t('Choose which page to show icon on.'),
      '#options' => $titles,
    );
  }

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

  return $form;
}   

【问题讨论】:

    标签: php drupal foreach drupal-fapi


    【解决方案1】:

    这很有意义。如果你的字段是这样声明的:

    $form[$name]['path_to_icon'] = array(
      '#type' => 'value',
      '#value' => $path, 
    );
    

    然后对于每个文件,您要更新相同的变量 - 'path_to_icon'。字段集键“$name”在这里无关紧要,因为它仅用于将表单字段组合在一起。

    你需要使用类似的东西:

    $form[$name]['path_to_icon_'.$name] = array(
      '#type' => 'value',
      '#value' => $path, 
    );
    

    那么你将在发布表单后获得多个值。

    但是,说实话,我不会使用 $name 作为变量名的元素,您应该使用自动递增 $fid(文件表中的文件 id)或任何其他唯一且安全的标识符之类的东西文件...

    【讨论】:

    • 非常感谢您的帮助,我现在可以立即使用了!关于$name 的命名的观点 - 我认为有一些领域可以改进/变得更加 Drupalish!
    【解决方案2】:

    我必须说,如果您将“#tree => TRUE”放在字段集的声明中:

    $form[$name] = array(
       '#type' => 'fieldset',
       '#title' => $name,
       '#tree' => TRUE
    );
    

    您不必在所有表单元素中都添加“_'.$name”。 Drupal 会将所有表单结果分组到以 $name 为键的数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 2011-08-30
      • 2014-11-10
      相关资源
      最近更新 更多