Skip to content

Instantly share code, notes, and snippets.

@Alexander-Pop
Last active June 11, 2024 12:19
Show Gist options
  • Save Alexander-Pop/b4f46881cb4d004b515dd9a297db421c to your computer and use it in GitHub Desktop.
Save Alexander-Pop/b4f46881cb4d004b515dd9a297db421c to your computer and use it in GitHub Desktop.
Magento 2 - redirect programmatically #magento2 #module #redirect
<?php
//In controller:
//No need to declare $this->resultRedirectFactory in construct as its auto declared in construct of \Magento\Framework\App\Action\Action to which custom controller should extend.
public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('routename/controllerpath/controllername');
$resultRedirect->setPath('');//home
return $resultRedirect;
}
//Other places
public function __construct(
\Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
) {
$this->resultRedirectFactory = $resultRedirectFactory;
}
/* Using Direct path, you need to pass action URL in a setPath() method */
//For redirect to cart page, Pass action path as checkout/cart,
//For Redirect to contact page,a parameter is contact
//For Redirect to a login page, a parameter is customer/account/login
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('checkout/cart');
return $resultRedirect;
//Pass Query string using above function by below methods,
$argument = ['id' => $getId, '_current' => true];
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('checkout/cart',$argument);
return $resultRedirect;
//Redirect to any link by direct URL using below way,
$resultRedirect = $this->resultRedirectFactory->create();
$url = 'http://mysite.com/magento2/checkout/cart';
$resultRedirect->setUrl($url);
return $resultRedirect;
//read also https://magento.stackexchange.com/questions/113251/redirect-controller-in-magento-2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment