Magento – Magento2: How to get config variable in block.php

blocksconfigurationmagento2

I want to get the value of config variable in my custom block.php file.

Can somebody help me in this?

So far, I did following this in my block file.

public function __construct(
     \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
     \Magento\Store\Model\StoreManagerInterface $storeManager
)
{
    $this->_scopeConfig = $scopeConfig;
    $this->_storeManager = $storeManager;
}

$this->_scopeConfig->getValue('carriers/freeshipping/free_shipping_subtotal', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

But I'm still not getting the value and showing error

( ! ) Fatal error: Uncaught Error: Call to a member function
dispatch() on null in
D:\wamp64\www\deboomhut0710\lib\internal\Magento\Framework\View\Element\AbstractBlock.php
on line 644 ( ! ) Error: Call to a member function dispatch() on null
in
D:\wamp64\www\deboomhut0710\lib\internal\Magento\Framework\View\Element\AbstractBlock.php
on line 644

Best Answer

The error you're getting is because your block needs to extend at least Magento\Framework\View\Element\AbstractBlock which is not the case.

It should look like this:

namespace Vendor\Module\Block;

use Magento\Framework\View\Element\AbstractBlock;

class MyBlock extends AbstractBlock {

    public function __construct(
     \Magento\Framework\View\Element\Context $context,
     \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
     \Magento\Store\Model\StoreManagerInterface $storeManager,
     array $data = []
    )
    {
        $this->_scopeConfig = $scopeConfig;
        $this->_storeManager = $storeManager;
        parent::__construct($context, $data);
    }
}
Related Topic