0

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 1

1

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"}}

2
  • 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
    – MikeMason
    Commented Aug 5, 2016 at 21:20
  • 1
    Yeah, it should be whatever you defined the module as, for example Name_ConfigValueWidget::configvalue.phtml. Commented Aug 6, 2016 at 0:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.