In Magento 1, to echo the store VAT number from a CMS page, I'd use {{config path="general/store_information/merchant_vat_number"}}
. How do I do this in Magento 2?
1 Answer
You can create a custom widget to do this.
Create a new module, Name_ConfigValueWidget
.
In etc/widget.xml
, use the following:
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
<widget id="config_value" class="Name\ConfigValueWidget\Block\Widget\ConfigValue"
placeholder_image="Magento_Cms::images/widget_block.png">
<label translate="true">Config Value</label>
<description translate="true">Product Showcase</description>
<parameters>
<parameter name="path" xsi:type="text" required="true" visible="true">
<label translate="true">Path</label>
</parameter>
</parameters>
</widget>
</widgets>
Now create the block class in Block/Widget/ConfigValue.php
:
<?php
namespace Name\ConfigValueWidget\Block\Widget;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\View\Element\Template;
use Magento\Widget\Block\BlockInterface;
class ConfigValue extends Template implements BlockInterface
{
protected $_scopeConfig;
public function __construct(
Template\Context $context,
ScopeConfigInterface $scopeConfig,
array $data
)
{
parent::__construct($context, $data);
$this->_scopeConfig = $scopeConfig;
$this->setTemplate('Name_ConfigValueWidget::configvalue.phtml');
}
public function getValue()
{
$path = $this->getData('path');
return $this->_scopeConfig->getValue(
$path,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
}
Now create the template file view/frontend/templates/configvalue.phtml
:
<span>
<?php /* @escapeNotVerified */ echo $block->getValue() ?>
</span>
After running setup:upgrade
and clearing the cache, you can use this widget in a CMS page like this:
{{widget type="Name\ConfigValueWidget\Block\Widget\ConfigValue" path="general/store_information/merchant_vat_number"}}
-
Hi Aaron, thank you for responding. I noticed you left some of your code in the above example -
AAllen_Sandbox::configvalue.phtml
. What should I put here, instead of AAllen_Sandbox? Thanks Aug 5, 2016 at 21:20 -
1Yeah, it should be whatever you defined the module as, for example
Name_ConfigValueWidget::configvalue.phtml
. Aug 6, 2016 at 0:00