0

Magento 2 Auto Redirect To Product Details Page If Category Have Only One Product

only one product in a category, just go to product detail page when clicking that category menu

i'm use Mage::app()->getFrontController()->getResponse()->setRedirect($url); in Magento 1.

this working in Magento 1 but not working in Magento 2

How to change the code.

1

To add a redirect in your file for Magento 2, you need to use Magento\Framework\Controller\ResultFactory in your file.

use Magento\Framework\Controller\ResultFactory;


Create a protected variable to use in your class.

protected $_resultFactory;

Now create an object for this class in your __construct function,

public function __construct(YOUR_OTHER_OBJECTS, ResultFactory $resultFactory)
{
    .. YOUR CODE ..
    $this->_resultFactory = $resultFactory; // Create object for ResultFactory
}

Now you can use this object to redirect to your URL like,

$redirect = $this->_resultFactory->create(ResultFactory::TYPE_REDIRECT);
$redirect->setUrl($url); // set your URL variable
return $redirect;
  • ok. I try this code – KGR Mar 2 '17 at 12:44

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.