How to redirect to previous page from my custom action in magento 2
Asked
Active
Viewed 4.7k times
4 Answers
58
In Your Controller write following code:
namespace Company\Module\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
class Actionname name extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
// Your code
$resultRedirect->setUrl($this->_redirect->getRefererUrl());
return $resultRedirect;
}
}
This code works for me.Hope it will help you too.
Vivek Kumar
- 5,115
- 2
- 24
- 50
ND17
- 5,181
- 9
- 50
- 78
-
Is their need to be xml file related to action in my module @ND17 – Learing_Coder May 08 '18 at 12:06
-
@PranayK First tell me what is your issue, If your action does not use for any page render than no need to add XML file – ND17 May 08 '18 at 13:21
-
if suppose i came to the list page when i need to go back, to home page i am getting the refererurl has list page url @ND17 – Learing_Coder May 08 '18 at 13:26
-
When you need to go back any action are you perform? for example click on something? – ND17 May 08 '18 at 13:29
-
yes I have Back link on click i need to get back to home page it is staying in list Page only. @ND17 – Learing_Coder May 08 '18 at 13:36
-
than set backlink url to homepage url no need to create action for that and in that action previous url is list page url so it will stay in list page – ND17 May 08 '18 at 13:41
21
This could also be a valid answer in a shorter form Magento 2.0.4
namespace Vendorname\Modulename\Controller\Adminhtml\Index;
class Fetch extends \Magento\Backend\App\Action
{
public function execute()
{
// TODO: Implement execute() method.
$this->_redirect($this->_redirect->getRefererUrl());
}
}
Ocastro
- 573
- 4
- 9
-
The
executemethod is expected to return either aMagento\Framework\Controller\ResultInterfaceor aMagento\Framework\App\ResponseInterface. Luckily the_redirectmethod does one of those so this is advisable:return $this->_redirect($this->_redirect->getRefererUrl());– clockworkgeek Jun 18 '18 at 14:15 -
-
4
Please use this code in your controller class:
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setRefererUrl();
return $resultRedirect;
Here resultRedirectFactory is a class variable that can be inherited in your class from there parents.
To check if referral URL is set or not, Please print the $_SERVER variable first. This code is working for me.
Sumit Verma
- 940
- 8
- 20
2
public function execute(){
$resultRedirect = $this->resultRedirectFactory->create();
try{
$this->messageManager->addSuccess(__('Redirection Sucessful.'));
}catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
}
$resultRedirect->setUrl($this->_redirect->getRefererUrl());
return $resultRedirect;
}
Amit Singh
- 1,765
- 3
- 19
- 37