3 namespace Drupal\Core\Form;
5 use Drupal\Core\Config\ConfigFactoryInterface;
8 * Provides access to configuration for forms.
10 * This trait provides a config() method that returns override free and mutable
11 * config objects if the configuration name is in the array returned by the
12 * getEditableConfigNames() implementation.
14 * Forms that present configuration to the user have to take care not to save
15 * configuration overrides to the stored configuration since overrides are often
16 * environment specific. Default values of form elements should be obtained from
17 * override free configuration objects. However, if a form reacts to
18 * configuration in any way, for example sends an email to the system.site:mail
19 * address, then it is important that the value comes from a configuration
20 * object with overrides. Therefore, override free and editable configuration
21 * objects are limited to those listed by the getEditableConfigNames() method.
23 trait ConfigFormBaseTrait {
26 * Retrieves a configuration object.
29 * The name of the configuration object to retrieve. The name corresponds to
30 * a configuration file. For @code \Drupal::config('book.admin') @endcode,
31 * the config object returned will contain the contents of book.admin
34 * @return \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
35 * An editable configuration object if the given name is listed in the
36 * getEditableConfigNames() method or an immutable configuration object if
39 protected function config($name) {
40 /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
41 if (method_exists($this, 'configFactory')) {
42 $config_factory = $this->configFactory();
44 elseif (property_exists($this, 'configFactory')) {
45 $config_factory = $this->configFactory;
47 if (!isset($config_factory) || !($config_factory instanceof ConfigFactoryInterface)) {
48 throw new \LogicException('No config factory available for ConfigFormBaseTrait');
50 if (in_array($name, $this->getEditableConfigNames())) {
51 // Get a mutable object from the factory.
52 $config = $config_factory->getEditable($name);
55 $config = $config_factory->get($name);
61 * Gets the configuration names that will be editable.
64 * An array of configuration object names that are editable if called in
65 * conjunction with the trait's config() method.
67 abstract protected function getEditableConfigNames();