Mastering Dynamic : Dynamic Page References Variable in Apex class

      Problem Statement How can we dynamically configure the page reference based on      

      the variable passed as the page name in an Apex class?


      Solutionwe can use the following piece of code to enable dynamic page reference setup

in an Apex class.

      //Code Starts Here

       ApexPage VFPageName =  [SELECT Name, NamespacePrefix FROM ApexPage          

       WHERE       Name = 'YourPageName' LIMIT 1];

      

      String pageName = VFPageName.Name;

     

     //Append namespace if the page is packaged

     if(String.isNotEmpty(VFPageName.NamespacePrefix)) {

        pageName = VFPageName.NamespacePrefix+'__' + pageName;

      }

     

      String partialPageUrl = '/apex/' + pageName;

      PageReference pdf = new PageReference(partialPageUrl);

      System.debug(pdf.getUrl());

      

      //Code Ends Here