logo

额外区块类型 (EBT) - 全新的布局构建器体验❗

额外区块类型 (EBT) - 样式化、可定制的区块类型:幻灯片、标签页、卡片、手风琴等更多类型。内置背景、DOM Box、JavaScript 插件的设置。立即体验布局构建的未来。

演示 EBT 模块 下载 EBT 模块

❗额外段落类型 (EPT) - 全新的 Paragraphs 体验

额外段落类型 (EPT) - 类似的基于 Paragraph 的模块集合。

演示 EPT 模块 滚动

滚动
03/10/2025, by Ivan

在表单上下文中使用 $config

您可以使用 配置表单 来了解 $config 如何获取用户输入的数据,并修改 {module}.settings.yml 文件中的数据。下面是一个在表单中声明 $config 对象的代码示例,您可以在表单设置的 PHP 文件中找到。

Drupal Core 的 ConfigFactory 类是读取和写入配置数据的方式,它用于根据指定配置文件的内容创建一个 Config 对象实例。新的 Config 对象随后可以用于对这些数据执行 CRUD 操作。

Config

表单定义示例(位于 example/src/Form/exampleSettingsForm.php):

namespace Drupal\example\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * 配置本网站的 example 设置。
 */
class ExampleSettingsForm extends ConfigFormBase {

  /** 
   * 配置设置.
   *
   * @var string
   */
  const SETTINGS = 'example.settings';

  /** 
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'example_admin_settings';
  }

  /** 
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      static::SETTINGS,
    ];
  }

  /** 
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config(static::SETTINGS);

    $form['example_thing'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Things'),
      '#default_value' => $config->get('example_thing'),
    ];  

    $form['other_things'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Other things'),
      '#default_value' => $config->get('other_things'),
    ];  

    return parent::buildForm($form, $form_state);
  }

  /** 
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // 获取配置。
    $this->configFactory->getEditable(static::SETTINGS)
      // 设置提交的配置项。
      ->set('example_thing', $form_state->getValue('example_thing'))
      // 您可以通过多次调用 set() 来同时设置多个配置。
      ->set('other_things', $form_state->getValue('other_things'))
      ->save();

    parent::submitForm($form, $form_state);
  }

}

路由文件(example.routing.yml):

example.settings:
  path: '/admin/config/example/settings'
  defaults:
    _form: '\Drupal\example\Form\ExampleSettingsForm'
    _title: 'example'
  requirements:
    _permission: 'administer site configuration'

通过使用 Config 对象,您可以简化从表单收集的数据。借助上面的表单设置代码,您就能够将表单数据存储到 {module}.settings.yml 中。

任何继承自 ConfigFormBase 的类都必须实现 getEditableConfigNames 方法,并返回它所编辑的配置字段名称数组。