Question

I am trying to add the store's phone number setup in Stores > Configuration > General > General > Store Information to the header in my theme. In a module I think this could be done using getValue() in \Magento\Framework\App\Config\ScopeConfigInterface but I cannot see a way how to use this inside a theme. So far I have added this to default.xml

 <referenceContainer name="header-wrapper">
      <block class="Magento\Framework\View\Element\Template" name="store.phone.number" template="Magento_Theme::phone.phtml" />
 </referenceContainer>

but I do not know how to get the phone number inside phone.phtml

Was it helpful?

Solution

I suggest you create your own block, which will extend the Magento\Framework\View\Element\Template class.

As the Magento\Framework\App\Config\ScopeConfigInterface is part of Magento\Framework\View\Element\AbstractBlock (the parent of the Template class) declared in $_scopeConfig, you can add the following function to your custom block:

public function getConfig()
{
    return $this->_scopeConfig;
}

Then in your template you can do:

$block->getConfig()->getValue('value/you/need');

Don't forget to update your layout like this:

<referenceContainer name="header-wrapper">
      <block class="Vendor\Module\Block\View\Element\Template" name="store.phone.number" template="Magento_Theme::phone.phtml" />
</referenceContainer>

OTHER TIPS

We can directly get a store config in the template by getting instance of Magento\Framework\App\Config\ScopeConfig:

 \Magento\Framework\App\ObjectManager::getInstance()
  ->get('Magento\Framework\App\Config\ScopeConfigInterface')
  ->getValue('value/you/need');

Technically, when someone asks for an instance of Magento\Framework\App\Config\ScopeConfigInterface, we will give it an instance of the Magento\Framework\App\Config\ScopeConfig. For example, we can get the default setting for grid or list mode:

$productListMode = \Magento\Framework\App\ObjectManager::getInstance()
   ->get('Magento\Framework\App\Config\ScopeConfigInterface')
   ->getValue('catalog/frontend/list_mode');

Note: Avoiding Using Object Manager directly. We should keep our templates clean. Try to add config to the block. Should follow the @Raphael answer.

Try this on Block, it is working for me after many search

$isEnabled = \Magento\Framework\App\ObjectManager::getInstance()
->get('Magento\Framework\App\Config\ScopeConfigInterface') ->getValue('section/group/field');

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top