1

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?

1

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();
 )
  • You are a legend!!!! That's 2 days of my life gone... Thank you kindly – Greg Jan 17 at 15:40
  • @aman, which class we need to inject for resultRedirectFactory? – jafar pinjar Mar 7 at 11:02
1

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, privacy policy and cookie policy

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