如何在Drupal 8中从数据库中写入和读取信息?

时间:2015-11-24 15:43:04

标签: php drupal drupal-8

我无法在Drupal 8中从数据库中写入和读取信息。

在Drupal 7中它看起来像这样:

# save & update
variable_set('variable', 'value');

# get
variable_get('test', false);

我知道在Drupal 8中看起来完全不同但是我尝试过的东西 不起作用。

1 个答案:

答案 0 :(得分:1)

要从配置对象中读取数据,请使用\Drupal::config()->get('system.site')->get('name')

要将数据设置为配置对象,首先需要加载可编辑配置实体,然后设置数据并最终保存。

$site_settings = \Drupal::configFactory()->getEditable('system.site');
$site_settings->set('name', 'Foo site');
$site_settings->save();

要将自定义配置保存到数据库,请创建配置yaml文件:

<强>模块/ MODULE_NAME /配置/安装/ custom.configuration.yml

custom-variable: 'hello world'

您还应该查看配置的架构文件:

<强>模块/ MODULE_NAME /配置/架构/ custom.configuration.schema.yml

custom-variable:
  type: 'string'
  label: 'Custom variable'
  description: 'A custom variable to store information in the database'