Magento 2 – How to Redirect from Controller

controllersmagento2redirect

In my controller BVZ\Customer\Controller\Index I'm doing a redirect using

return $this->_redirect('customer/index/firstAccess');

When the code execute, the request are made (see the print below)
below
enter image description here

but the url in browser stay in the same place.

how can i make the page redirect to 'customer/index/firstAccess' and not just make the request?

all code of my controller

<?php

namespace BVZ\Customer\Controller\Index;

class CustomerExists extends \Magento\Framework\App\Action\Action {

  public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Customer\Api\AccountManagementInterface $customerAccountManagement
  ) {
        parent::__construct($context);
            $this->resultJsonFactory = $resultJsonFactory;
            $this->customerAccountManagement = $customerAccountManagement;
  }

  public function execute() {
    $cpfcpnj = $this->getRequest()->getParam('cpfcpnj');

    $vowels = array("-", ".","/");
    $cpfcpnj = str_replace($vowels, "", $cpfcpnj);

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $customerObj = $objectManager->create('Magento\Customer\Model\ResourceModel\Customer\Collection');
    $collection = $customerObj
                  ->addAttributeToSelect('*')
                  ->addAttributeToFilter('taxvat',$cpfcpnj)
                  ->load()
                  ->getFirstItem();

  if($collection->getId()) {

      if($collection->getData('firstAccess')!=0){

          //email reset
          return $this->_redirect('customer/account/ResetPasswordPost');
          $return = "first";
      } else {
          $return = "exists";
      }

  } else {
      $return = "new";
  }

  $result = $this->resultJsonFactory->create();
  return $result->setData($return);

Best Answer

public function execute()
{
    $resultRedirect = $this->resultRedirectFactory->create();
    $resultRedirect->setPath('routername/controllerpath/controllername');
    return $resultRedirect;
}
Related Topic