In previous versions of Drupal you would see values from settings.php on the coniguration pages. For instance $conf['mymodule_setting_value'] = 'My Value';
would display "My Value" in the text field and whenever you would try make a change to the field and try hit save button the value of the field would reset to the value specified in settings.php
. However in Drupal 8 overridinen configuration form values in settings won't reflect in the form.
There is an issue on Drupal.org for that and developers already found a solution and it should be fixed in Drupal core soon.
Below I am going to provide an example of a simple config form value override in settings.php
.
Drupal 8 configuraiton form example:
/**
* @file
* Contains \Drupal\mymodule\Form\BasicSettingsForm.
*/
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Form builder for the mymodule basic settings form.
*/
class BasicSettingsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'mymodule_basic_settings_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['mymodule.settings'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('mymodule.settings');
$form['text_val'] = [
'#type' => 'textfield',
'#title' => $this->t('My Module setting'),
'#default_value' => $config->get('text_val'),
];
$form['group_setting1'] = [
'#type' => 'textfield',
'#title' => $this->t('Setting 1'),
'#default_value' => $config->get('group.setting1'),
];
$form['group_setting2'] = [
'#type' => 'textfield',
'#title' => $this->t('Setting 2'),
'#default_value' => $config->get('group.setting2'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$config = $this->config('mymodule.settings');
$config->set('text_val', $form_state->getValue('text_val'));
$config->set('group.setting1', $form_state->getValue('group_setting1'));
$config->set('group.setting2', $form_state->getValue('group_setting2'));
$config->save();
}
}
To override configuration values use the following format in settings.php
:
$config['mymodule.settings'] = [
// Simple text value override.
'text_val' => 'Value from settings.php',
// Groupped values.
'group' => [
'setting1' => 'Value 1',
'setting2' => 'Value 2',
],
];
You could also use drush
to see the values of your configuration forms by using the following command:
drush cget mymodule.settings
$settings variable
You could also use $settings
in settings.php
to control your module settings or any other conditional logic.
Add the following to settings.php
$settings['my_setting'] = 'My Setting Value';
And this is how you would access the variable in your code:
use Drupal\Core\Site\Settings;
function my_function() {
$mySetting = Settings::get('my_setting', NULL);
}