【问题标题】:How to write and read informations from the database in Drupal 8?如何在 Drupal 8 中写入和读取数据库中的信息?
【发布时间】:2015-11-24 15:43:03
【问题描述】:

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

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

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

# get
variable_get('test', false);

我知道在 Drupal 8 中它看起来完全不同,但我尝试过 不工作。

【问题讨论】:

    标签: php drupal drupal-8


    【解决方案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 文件:

    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'
    

    【讨论】:

    • 只需一次更改即可使用。 GET 应该看起来像这样 $system = \Drupal::config('system.site'); $value = $system->get('variable');
    • @WalterWhite get() 仅用于不可变配置。 getEditable() 用于可变配置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多