Magento 2 how to get config value

The transmission of configuration values from the backend to the front end of the website makes it easy for store owners to choose the configuration for each of their stores. In the following article, we will learn Magento 2 how to get config value.

If you still don’t know how to Create Magento 2 theme options please click here to read it before.

1. Get config from file layout

Continue our example, we will get value off config enable default banner on default.xml

Crate app/code/Magerubik/ThemeOptions/default.xml file with below content

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="page.top">
            <block ifconfig="mrThemes/general/defaul_top_banner_enable" class="Magento\Framework\View\Element\Template" name="magerubik-topbanner" template="Magerubik_ThemeOptions::topbanner.phtml"/>
        </referenceBlock>
    </body>
</page>

Then create app/code/Magerubik/Themeoptions/view/frontend/templates/topbanner.phtml file with below content to check it working

add banner here
Magento default config value

Go to backend change config value then clear cache to check it working

If you see the below screen evrything is fine.

Magento default config test

2. Create helper to get config value

Continue our example, we will Crate app/code/Magerubik/Themeoptions/Helper/Data.php file with below content

<?php
namespace Magerubik\Themeoptions\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function getConfig($cfg=null)
    {
        if($cfg) return $this->scopeConfig->getValue( $cfg, \Magento\Store\Model\ScopeInterface::SCOPE_STORE );
        return $this->scopeConfig;
    }
}

Then update app/code/Magerubik/Themeoptions/view/frontend/templates/topbanner.phtml file with below content to check it working

<?php
$themeConfig = $this->helper('Magerubik\Themeoptions\Helper\Data');
$media = $this->helper('\Magento\Cms\Helper\Wysiwyg\Images')->getBaseUrl();
?>
<div class="top_banner">
	<img src="<?= $media . 'themeoptions/' .$themeConfig-> getConfig('mrThemes/general/top_banner_image');?>"/>
</div>

Clear cache then go to frontend

If you see the below screen evrything is fine.

Magento default config test

3. Get config value by block Layout

Go to app/code/Magerubik/Themeoptions/view/frontend/templates/topbanner.phtml file add below content then clear cache to check it working

<?php 
$config = $block->getLayout()->createBlock(\Magento\Config\Block\System\Config\Form::class);
echo $config->getConfigValue('mrThemes/general/top_banner_image');

Ok now you know Magento 2 how to get config value. In the next posts we will learn how to Override Magento 2 template. Contact us if you face any problems during the installation process.

You can download the demo code for this entire series from GitHub