After saving data always you need to redirect to custom URL or sometime to previous page. so in this article I want to share a pace of redirect cod.
Assume your controller name is Test and your action is name Index. AS you know we have a class to each action.
namespace Darvishani\Module\Controller\Test;
use Magento\Framework\Controller\ResultFactory;
class Index extends \Magento\Framework\App\Action\Action
{
protected $resultFactory;
public function __construct(
\Magento\Framework\Controller\ResultFactory $resultFactory,
\Magento\Framework\App\Action\Context $context
)
{
$this->resultFactory = $resultFactory;
parent::__construct($context);
}
public function execute()
{
$redirect = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);
$redirect->setUrl('frontname/controller/action');
return $redirect;
}
}
How about when you want to redirect to previous page.
namespace Darvishani\Module\Controller\Test;
use Magento\Framework\Controller\ResultFactory;
class Index extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl($this->_redirect->getRefererUrl());
return $resultRedirect;
}
}