Dynamic PageReference Configuration in Salesforce Apex

still code is coming in one line Salesforce Apex code demonstrating dynamic PageReference configuration

Dynamic PageReference Configuration in Salesforce Apex

Dynamically generating a PageReference in Salesforce Apex is a common requirement when working with Visualforce pages, especially in managed packages or reusable components.

1. Apex Code Implementation

Below is the properly formatted Apex code. Line breaks are preserved using HTML-safe formatting so it renders correctly in Blogger and WordPress.

// Query the Visualforce page metadata
 ApexPage vfPage = [
 SELECT Name, NamespacePrefix
 FROM ApexPage
 WHERE Name = 'YourPageName'
 LIMIT 1
 ];
 
 // Store the page name
 String pageName = vfPage.Name;
 
 // Append namespace if the page belongs to a managed package
 if (String.isNotEmpty(vfPage.NamespacePrefix)) {
 pageName = vfPage.NamespacePrefix + '__' + pageName;
 }
 
 // Build the partial Visualforce URL
 String partialPageUrl = '/apex/' + pageName;
 
 // Create the PageReference
 PageReference pdf = new PageReference(partialPageUrl);
 
 // Debug the generated URL
 System.debug(pdf.getUrl()); 

2. Important Note

Some CMS platforms collapse whitespace inside <pre> blocks. Using HTML line break entities (&#10;) ensures the code always renders in a clean, multi-line format without breaking copy functionality.