是否可以在同一模块中创建的控制器中编辑/创建模块的配置变量?
例如: 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();
}
答案 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);