在 Drupal Forms 中拥有 50 个状态下拉框的最有效方法
我知道一种方法是在数据库中建立一个包含所有状态的表,然后您可以在表单中读取它。你们认为还有更简单的方法吗?
我觉得要求这样的东西很糟糕,因为它是如此基本,但是我认为像这样简单的东西已经在 Drupal 中实现了。
I know that one way is to have a table in database with all the states and then you would read it in your form. Is there any easier way in your opinion guys ?
I feel bad asking for something like this since it is so elementary however I would suppose something as simple like this would already be implemented in Drupal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
无需访问数据库。为自己构建一个返回状态数组的函数。
No need to hit the database. Build yourself a function that returns an array of the states.
如果您使用 Drupal 的 FormAPI 构建表单,则只需在模块代码中包含状态数组即可,因为名称和缩写不会很快发生更改。
如果您想保持代码整洁,可以使用variable_set() 将状态数组保存为Drupal 变量,然后使用variable_get() 检索它。您确实不需要为此类事情而操心数据库。
If you're building the form using Drupal's FormAPI you could just include the array of states in your module code since the names and abbreviations shouldn't be changing any time soon.
If you're trying to keep your code clean, you could save an array of states as a Drupal variable using variable_set() and then retrieve it using variable_get(). You really shouldn't need to bother with the database for that kind of thing.
当然,这是一种方法。您可以将状态列表存储为变量并调用它。
只要它是一个数组。您还可以有一个返回状态的内部函数。
That is one way to do it, sure. You can store a list of states as a variable, and call it.
So long as it's an array. You could also have an internal function that returns the states.
或者将其存储在平面文件中并读取它。例如,
平面文件 =
函数:
一切都很丑陋,但您至少可以独立编辑该文件,并且如果您有更大的列表,则可能会很好地工作。有一百万种方法可以包含该列表 - 使用 exec、fgetcsv/file 等...
但我认为 ceejayoz 解决方案是最好的。我可能会将这些类型的实用函数分拆成一个单独的包含文件,以保持自己的干净。
Or store it in a flat file and read it in. Eg
Flat file =
Function:
All pretty ugly, but you at least can edit that file independently, and may work well if you have a larger list. Theres a million ways you could have the list included - using exec, fgetcsv/file, etc....
But I think ceejayoz solution is the nicest. I'd probably spin out those sorts of utility functions into a seperate include to keep it clean myself.
国家/地区代码 API 模块还提供了包含美国各州的地区代码 API 模块。使用此模块,您可以通过调用
regions_api_iso2_get_options_array('US')
获取适合 Form API 选择元素的数组。The Country codes API module also provides a Regions codes API module which include US states. With this module, you can get an array suitable for a Form API select element by calling
regions_api_iso2_get_options_array('US')
.当我尝试 Geonames 模块时才想起这个问题。在众多其他功能中,Geonames 包括函数“geonames_us_states()”,该函数返回由州的两个字母代码键入的美国州数组。
Just remembered this question as I was experimenting with the Geonames module. Among tons of other features, Geonames includes the function "geonames_us_states()" which returns an array of U.S. states keyed by the states' two letter code.