How to write and get config values by scope in Magento 2

- Fire development, Magento 2

Magento 2 import export debug log

In the following article, we’d like to draw your attention to an essential feature of Magento 2 – the ability to write and get config values by scope. Unfortunately, it is less documented than others, but we are here willing to help you! Note that you may need to apply different settings to different stores programmatically. Everything else is mentioned below. For more tips and advice, follow this link: Magento 2 Developer’s Cookbook.

'

How to write and get config values by scope in Magento 2

It is not a secret that all adminhtml settings are saved and stored in the core_config table in your Magento 2 database. To get values, they use its path, a string that indicates a way to and a variable name. Use this path to get or set values by Magento 2 core methods. 

According to Magento2 Blog, you may use:

  • \Magento\Framework\App\Config\Storage\WriteInterface
  • \Magento\Framework\App\Config\ScopeConfigInterface

WriteInterface can be utilized for writing config values to the database while ScopeConfigInterface is helpful for reading config values from it

Let’s explore several sample codes for a better understanding.

How to write store config values by scope in Magento 2

Below, you can find a code snippet that illustrates how to write store config values by scope:

Call the setConfig() method with a given value since it stores the value into a defined path for all websites. The method generates a new setting (a line of code in the core_config table). The change is applied to every specified website. Third and fourth params on the save method should be utilized. Use a unique path, value, scope, and its ID. However, if you do not need to use scope, you write the value to default: your store ID is 0. Also, note that it is possible to store values to scopes by “website” or “store.“

How to get and read store config values by scope in Magento 2

To read the data by store, use the following code snippet:

In this situation, use the getValue() method and add a second param with scope. The example above uses a website scope. As a result, you will get the stored value for the current website.

Final Words

Now, you know how to write and read config values by scope in Magento 2. The feature is necessary for those programmers who work on multi-store shops and need to set and read config values by scope programmatically. If you still have any questions, follow this link: Magento 2 – write and get config values by scope.

'