Thursday, June 27, 2013

how to redirect referer page after login in magento


>> Only admin setting (step 1) needed to redirect customer after login. Using this I'm showing how will you restrict a page only for registered customer. If someone click the url www.example.com/restricted_page.html, it'll redirect to login page. Then after login it should redirect back to the www.example.com/restricted_page.html.
Here's how I did it :

    Step 1: Go to Admin => System => Configuration => Customer Configuration => Login Options => "Redirect Customer to Account Dashboard after Logging in" set it "No".
 
    Step 2: If you're using a module page then you've the controller Action method like:
  
            public function indexAction()
            {
                // use here to restrict the page //
                if(!Mage::helper('customer')->isLoggedIn()){
                    Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
                       $this->_redirect('customer/account/login');
                }
                //        End your addition //

              
                $this->loadLayout();   
                $this->renderLayout();
            }
            you can use one of this code to redirect:
 
            Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
            $this->_redirect('customer/account/login');
         
                                OR
                             
            $this->_redirect('customer/account/login/referer/'.Mage::helper('core')->urlEncode('Restricted Page Url'));
          
    Step 3: (optional) If you're using a cms page then follow this step:
          
            In your admin CMS section include a phtml page and write the below code at the top of the page:
          
            if(!Mage::helper('customer')->isLoggedIn()){
                Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
                $this->_redirect('customer/account/login');
            }
          
>> Now if you want to use the login url inside a page with referer url follow this:
      
    <?php $referer = Mage::helper('core')->urlEncode(Mage::helper('core/url')->getCurrentUrl()); ?>
    <a href="<?php echo Mage::getUrl('customer/account/login', array('referer' => $referer)) ?>">Login</a>