如何使用Hook_install()将默认值添加到数据库表中?
-
16-10-2019 - |
题
我正在创建一个具有自己的几张表格架构的自定义模块。这些表需要在它们中填充一些值以使模块工作(默认位置,选择选项等)。
在Hook_install期间,将默认值插入这些表中的最佳实践方法是什么?
由于drupal_write_record不可用,我可以使用db_query,但是我只想确保我不会这样做。
解决方案
更好的方法是在里面做 hook_enable();在调用钩子时,已经安装了模块,并且其数据库的架构可用于Drupal,并可以使用 drupal_write_record()
. 。由于挂钩始终调用启用模块,而不仅仅是安装模块时,挂钩实现应检查是否还没有添加这些数据库行(例如,它应该使用包含Boolean值的Drupal变量) 。
作为使用的模块的示例 hook_enable()
出于类似目的,您可以检查 forum_enable(), , 或者 php_enable() (添加“ PHP代码”输入格式)。
function php_enable() {
$format_exists = (bool) db_query_range('SELECT 1 FROM {filter_format} WHERE name = :name', 0, 1, array(':name' => 'PHP code'))->fetchField();
// Add a PHP code text format, if it does not exist. Do this only for the
// first install (or if the format has been manually deleted) as there is no
// reliable method to identify the format in an uninstall hook or in
// subsequent clean installs.
if (!$format_exists) {
$php_format = array(
'format' => 'php_code',
'name' => 'PHP code',
// 'Plain text' format is installed with a weight of 10 by default. Use a
// higher weight here to ensure that this format will not be the default
// format for anyone.
'weight' => 11,
'filters' => array(
// Enable the PHP evaluator filter.
'php_code' => array(
'weight' => 0,
'status' => 1,
),
),
);
$php_format = (object) $php_format;
filter_format_save($php_format);
drupal_set_message(t('A <a href="@php-code">PHP code</a> text format has been created.', array('@php-code' => url('admin/config/content/formats/' . $php_format->format))));
}
}
从这些挂钩实现中所示,该代码可能必须始终执行钩子。这也可能是代码只需要执行一次,因为在情况下,添加到数据库中的默认值无法从用户更改为数据库,而用户没有用户界面可以更改/删除这些值。
其他提示
我会和 db_query
/ db_insert
(D6 / D7)在Hook_install()中。
这不是不良的习惯(没有人强迫您使用 drupal_write_record()
).
人们禁用和重新启用模块并不少见,在这种情况下,您的代码在 hook_enable()
每次都会开火。这不好。
不隶属于 drupal.stackexchange