【发布时间】:2015-11-24 15:43:03
【问题描述】:
我无法在 Drupal 8 中写入和读取数据库中的信息。
在 Drupal 7 中它看起来像这样:
# save & update
variable_set('variable', 'value');
# get
variable_get('test', false);
我知道在 Drupal 8 中它看起来完全不同,但我尝试过 不工作。
【问题讨论】:
我无法在 Drupal 8 中写入和读取数据库中的信息。
在 Drupal 7 中它看起来像这样:
# save & update
variable_set('variable', 'value');
# get
variable_get('test', false);
我知道在 Drupal 8 中它看起来完全不同,但我尝试过 不工作。
【问题讨论】:
要从配置对象中读取数据,请使用\Drupal::config()->get('system.site')->get('name')。
要将数据设置为配置对象,您首先需要加载可编辑的配置实体,然后设置数据并最后保存。
$site_settings = \Drupal::configFactory()->getEditable('system.site');
$site_settings->set('name', 'Foo site');
$site_settings->save();
要将自定义配置保存到数据库,请创建配置 yaml 文件:
modules/MODULE_NAME/config/install/custom.configuration.yml
custom-variable: 'hello world'
您还应该为您的配置提供一个架构文件:
modules/MODULE_NAME/config/schema/custom.configuration.schema.yml
custom-variable:
type: 'string'
label: 'Custom variable'
description: 'A custom variable to store information in the database'
【讨论】:
$system = \Drupal::config('system.site'); $value = $system->get('variable');