Saturday 1 December 2012

How to return or redirect a visual force(VF) page from JS & controller

In many instances we need to return a page on some action. There are various ways to return a page.

1. If you want to display your object home page from controller, i.e, page displays when u click on the object tab,

    // in this example when this function will be called, it will return the pageReference of object.
   
    public pageReference cancel(){

         // I have hardcoded the link of the object home page in this example.                   
         pageReference pr = new pageReference('/a0E/o');

         return pr;
    }

 2. If you want to display any VF page.

        public pageReference cancel(){

            return Page.test_page;   // here test_page is the name of VF page.  
      
        }
   
    or

        public pageReference cancel(){

            PageReference pr;

            pr = Page.test_page;// here test_page is the name of VF page.
       
            pr.setRedirect(true);

            return pr;             
         }
   


3. if you want to return edit or view page of a record. view() and edit() internally calls the page assigned in the object for view and edit. If no page is assigned
then it opens default page.

    // this function saves the record and display its details
    public pageReference save(){

        insert(obj); // obj is the reference of the Object which is currently in use.

        return (new ApexPages.StandardController(obj)).view();

    }

    // this function opens the record in editable form
    public pageReference edit(){

        // obj is the reference of the Object which is currently in use.

        return (new ApexPages.StandardController(obj)).edit();

    }

4. If you want to display your object home page from javascript

    window.onload=function redirect(){

        parent.frames.location.replace('/a0F/o');

        // I have hardcoded the link of the object home page in this example.

    }

5. if you want display detail page of a record from javascript

    function redirect(){

         // Obj_Test__c is API name of my object.     and Obj_Test__c should be mapped to the current  
         object id in the controller.

         parent.frames.location.replace('/{!Obj_Test__c.Id}');

    }   

6. If you want to return to the home page of a object, through javascript using global variable.
   
    window.onload = function redirect()
    {
         // this will return the home page of Obj_Test__c.          
         window.parent.location.href = "/{!$ObjectType.obj_Test__c}";
    }

7. if you want to close a window from javascript

    function closeWindow(){
            window.close(); // this will close the current window.
    }

No comments:

Post a Comment