Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

In this tuto, I'll show you how to override configuration from custom module in Drupal 8.

  • Create a module (codimth_config_override used as an example)
name: Config Override Example
description: Provide a config override from custom module
package: CodimTh
type: module
core: 8.x

 

  • Create a codimth_config_override.services.yml, and put:
services:
  codimth_config_override.overrider:
    class: Drupal\codimth_config_override\Config\ConfigExampleOverrides
    tags:
      - {name: config.factory.override, priority: 5}

config.factory.override is the important thing here, others are up to you to change.

 

  • Define the class which implements ConfigFactoryOverrideInterface:
<?php
namespace Drupal\codimth_config_override\Config;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryOverrideInterface;
use Drupal\Core\Config\StorageInterface;

/**
 * Example configuration override.
 */
class ConfigExampleOverrides implements ConfigFactoryOverrideInterface {

    /**
     * {@inheritdoc}
     */
    public function loadOverrides($names) {
        $overrides = array();
        if (in_array('system.site', $names)) {
            $overrides['system.site'] = ['name' => 'My site name!'];
        }
        return $overrides;
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheSuffix() {
        return 'ConfigExampleOverrider';
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheableMetadata($name) {
        return new CacheableMetadata();
    }

    /**
     * {@inheritdoc}
     */
    public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
        return NULL;
    }

}

"system.site" which is the YML you wish to override. The value assigned to $overrides['system.site'] is changed to what you wish to be placed.

to get the original value juste use:

$name = \Drupal::config('system.site')->getOriginal('name', FALSE);

Next steps

  • Clear your Drupal 8 caches. To do this I use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.
  • Now, enable the module, and you should be able to see if your site name is overriden or not yet.
  • I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.
  • This code can be found and downloaded from https://github.com/codimth/codimth_config_override.

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon