1

我一直在研究一种方法来限制 contrib 位置模块附带的下拉列表中的可用国家/地区。我认为 hook_form_alter 是处理仅显示某些国家/地区的方法,但是从手开始一个 hook_form_alter 片段并不是我有能力实现的。经过多次谷歌搜索后,我无法找到让我开始的代码片段。

我现在正在做的一个项目只允许来自美国和加拿大的注册,所以我想将该下拉菜单限制在这两个国家/地区。调用国家列表的函数是location_get_iso3166_list,数组是$countries。位置模块用于填充内容配置文件模块中的片段。

我在网上发现了一些帖子,建议只注释掉 .inc 文件中不需要的国家/地区...这不是该项目的选项,因为我们处于多站点设置中,因此将其更改为该模块将影响其他站点。我想我需要在 template.php 中添加一个 hook_form_alter 片段

任何帮助是极大的赞赏。

谢谢你!-杰夫

4

2 回答 2

0

你是对的,hook_form_alter()是一个好的开始。如果您希望更改内容类型表单,我使用的一种方法是创建一个非常小且简单的自定义模块来实现hook_form_alter()。可以在下面找到有关创建此模块的详细信息/说明。

例如,我将此模块称为“custom_countries”,如果您想更改名称,您可以随时重命名文件并稍后在其中进行搜索和替换。

首先,您需要在模块文件夹(sites/all/modules等)中创建一个新文件夹。(从现在开始创建的所有文件都应该放在这个文件夹中)。接下来,创建一个名为的新文件custom_countries.info并将以下内容放入并保存:

name = "Custom Countries"
description = "Changes the list of countries available from Location module for certain content types"
core = 6.x

接下来,创建另一个名为 的文件custom_countries.module,将以下代码放入其中并保存文件:

<?php
/**
 * @file custom_countries.module
 * Module to change the countries options of location module
 * for certain content type(s)
 */

/**
 * Implementation of hook_form_alter()
 */
function custom_countries_form_alter(&$form, $form_state, $form_id) {
  // Replace "YOUR_CONTENT_TYPE with the name of the content type desired
  if ($form_id == 'YOUR_CONTENT_TYPE_node_form') {
    $form['#after_build'][] = 'custom_countries_after_build';
  }
}

/**
 * Make changes to countries field after all fields are rendered
 */
function custom_countries_after_build($form_element, &$form_state) {
  // Replace FIELD_NAME with the machine name of the location field for your content type
  $form_element[FIELD_NAME][0]['country']['#options'] = array(
    'ca' => 'Canada',
    'us' => 'United States',
  );
  return $form_element;
}

重要提示:请务必阅读评论并将“YOUR_CONTENT_TYPE”更改为您的位置字段所在的内容类型的机器名称(如果使用默认的 content_profile 设置,可能只是“配置文件”)。此外,将“FIELD_NAME”更改为位置字段的机器名称。

最后,在admin/build/modules.

现在,当您创建/编辑您指定的内容类型时,您只会在国家列表中看到 2 个选项。使用此方法,您现在也可以轻松地更改其他表单。

这个想法来自Make Location 表单字段可用于 hook_form_alter()。如果将来您决定添加其他国家/地区,可以在http://api.lullabot.com/location_get_iso3166_list/5找到完整的键/值对列表

于 2011-06-02T20:51:29.787 回答
0

如果您使用的是 Drupal 7,则编辑相关字段设置并从后端限制国家/地区选项。

于 2016-11-14T22:00:27.923 回答