2

I am trying to get controller URL in my Block, but I am not able to get it. I tried this code :

$storeId = $this->_storeManager->getDefaultStoreView()->getStoreId();
$url = $this->_storeManager->getStore($storeId)->getUrl("zipcode/index/index");

This code throws an exception like :

Undefined property: Tm\Zipcode\Helper\Data::$_storeManager

I can access controller manually at store_name/zipcode/index/index

4
  • 1
    $url = $this->getUrl('zipcode/index/index');
    – Bhavik
    Feb 23, 2017 at 9:24
  • I tried that too, it shows undefined method getUrl()
    – jackson5
    Feb 23, 2017 at 9:36
  • r u extend your block class with \Magento\Framework\View\Element\Template ?
    – Bhavik
    Feb 23, 2017 at 9:39
  • @Bhavik yes I did it.
    – jackson5
    Feb 23, 2017 at 9:49

2 Answers 2

6

if you have created your block class by extending \Magento\Framework\View\Element\Template

In Your phtml file use following code :

$block->getUrl("zipcode/index/index");

To get the url.

if you need the url in the block class itself use :

$this->getUrl("zipcode/index/index");

Comment if you need more help.

2
  • I need the URL in the block class itself, not in the phtml. file
    – jackson5
    Feb 23, 2017 at 10:10
  • then use $this->getUrl(...)
    – Marius
    Feb 23, 2017 at 10:18
0

Modify your Tm\Zipcode\Helper\Data class and make the constructor look like this

protected $_storeManager;
public function __construct(
    ...
    \Magento\Store\Model\StoreManagerInterface $_storeManager,
    ...
) {
    ...
    $this->_storeManager = $_storeManager;
    ...
}

Then the storeManager variable will be available in your class

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.