How can I update existing config from a custom module's config/install yamls?
-
13-02-2021 - |
Question
I added some config yml files to my module's config/install directory so that it is installed directly when installing my module, it works well only if there isn't a config file with the same name installed already and only if it's the first install. So my question is there a way to update the config files already installed with my module's config file, and delete them when uninstalling the module ?
Solution
A module install should not update config. If you want to update existing config, your module should implement hook_update_N()
(see docs) instead.
However, you could add a dependencies: enforced
section to your YML config files. This will remove your existing config on module uninstall, and install the newest config on module reinstall. This way you can "emulate" a simple update mechanism for your own, private custom module. See doc for enforced config dependencies
OTHER TIPS
You can update custom config with a settings form you build. In a custom module custom_mailing add a file called custom_mailing.routing.yml add the following route:
custom_mailing.route_admin_settings:
path: '/admin/config/mailing'
defaults:
_title: 'Custom mailing'
_form: '\Drupal\custom_mailing\Form\AdminSettingsForm'
requirements:
_permission: 'administer custom_mailing settings'
Now I want a boolean value to be editable. I create a file in a map config/install
called custom_mailings.settings.yml with the following content:
mailsettings:
enabled: 0
In a module called custom_mailing. Inside src/Form
add file called AdminSettingsForm.php
.
<?php
namespace Drupal\custom_mailing\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class AdminSettingsForm.
*
* @package Drupal\custom_mailing\Form
*/
class AdminSettingsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'custom_mailing_admin_settings_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'custom_mailing.settings',
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('custom_mailing.settings');
$form['mailsettings'] = [
'#tree' => TRUE,
'#type' => 'fieldset',
'#title' => $this->t('Email settings'),
];
$form['mailsettings']['enabled'] = [
'#type' => 'checkbox',
'#title' => $this->t('Enable sending of e-mails.'),
'#default_value' => $config->get('mailsettings.enabled'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config('custom_mailing.settings');
$config->set('mailsettings', $form_state->getValue('mailsettings'));
$config->save();
parent::submitForm($form, $form_state);
}
}