Magento 2.1: Invoke urlBuilder->getUrl() in a controller in a custom module
actually from controller you can use
$this->_url->getUrl('yourmoduleurl/index/index')
If your controller extend Magento\Framework\App\Action\Action
you should follow rules of creation of the controller. So you should implement dependency injection of the parent class constructor (Magento\Framework\App\Action\Action
):
/**
* @param Context $context
*/
public function __construct(Context $context)
{
parent::__construct($context);
$this->_objectManager = $context->getObjectManager();
$this->_eventManager = $context->getEventManager();
$this->_url = $context->getUrl();
$this->_actionFlag = $context->getActionFlag();
$this->_redirect = $context->getRedirect();
$this->_view = $context->getView();
$this->messageManager = $context->getMessageManager();
}
Your construct method should look like this after a modifications:
/**
* @param Context $context
* @param UrlInterface $urlBuilder
*/
public function __construct(
Context $context,
UrlInterface $urlBuilder
) {
parent::__construct($context);
$this->urlBuilder = $urlBuilder;
}
NOTE: do not forget to remove old var/generation
directory after implementing of modifications, because there are stored the generated files of controllers.