3

I want to redirect to a external URL in my controller but not in the execute() function.

This code works fine and the result is a redirect to google:

public function execute()
{
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($this->session->isLoggedIn()) {
        $resultRedirect->setUrl('https://www.google.co.uk');
        return $resultRedirect;
    }
 )

However, this code is not working:

public function execute()
{
    $this->testRedirect();
 )

public function testRedirect(){
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($this->session->isLoggedIn()) {
        $resultRedirect->setUrl('https://www.google.co.uk');
        return $resultRedirect;
    }
}

This code doesn't redirect and leave the page blank.

What am I doing wrong?

2 Answers 2

3

As per the code you are calling another function from execute i.e testRedirect() which is returning object resultRedirect, but with the object you are not doing anything in execute function. That is why it is showing blank page.

Try this if it works:

public function execute()
{
    return $this->testRedirect();
 )
2
  • You are a legend!!!! That's 2 days of my life gone... Thank you kindly
    – Greg
    Jan 17, 2019 at 15:40
  • @aman, which class we need to inject for resultRedirectFactory? Mar 7, 2019 at 11:02
5

This code is worked for me

protected $resultRedirectFactory;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Controller\Result\Redirect $resultRedirectFactory
    ) {

        $this->resultRedirectFactory = $resultRedirectFactory;
        parent::__construct($context);
    }

    public function execute()
    {
                $resultRedirect = $this->resultRedirectFactory->create();
                $redirectLink = 'External Url'; 
                $resultRedirect->setUrl($redirectLink);
                return $resultRedirect;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.