在Drupal 8中的控制器中编辑自定义模块的配置变量

时间:2018-07-26 13:46:16

标签: controller drupal-8

是否可以在同一模块中创建的控制器中编辑/创建模块的配置变量?

例如: module_name / src / Controller / MyController.php:

class MyController extends ControllerBase {

    public function x($y) {
        $config = \Drupal::config('module_name.settings');
        $config->set('var1', $y)->save();
    }
}

module_name.module:

function module_name_page_attachments(array &$page) {
  $config = \Drupal::config('module_name.settings');
  var_dump($config->get('var1'));
}

module_name / config / install / module_name.settings.yml:

var1: 0

module_name / src / Form / moduleNameSettings.php:

class moduleNameSettings extends ConfigFormBase {

    protected function getEditableConfigNames() {
        return [
            'module_name.settings',
        ];
    }


    public function submitForm(array &$form, FormStateInterface $form_state) {
        parent::submitForm($form, $form_state);
        $config = \Drupal::config('module_name.settings');

        $this->config('module_name.settings')
            ->set('var1', $config->get('var1'))
            ->save();
    }

1 个答案:

答案 0 :(得分:-1)

要更新配置变量的值,请使用以下代码:

$config_factory = \Drupal::configFactory();
$config = $config_factory->getEditable('module_name.settings'); //Fetch the drupal configuration settings
$config->set('foo', '1');
$config->save(TRUE);