function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
gribisgribis 

How can I generate PageReferences to a specific view(e.g. New Contact) in VF controller APEX code?

I am trying to generate a PageReference to a new object, and pre-populate the object with some values. Additionally, I need to specify a return page. All this is doable in javacript or within the VF page.
Code:
...<apex:stylesheet value="{!URLFOR($Resource.pdfresources, 'styles.css')}"/>...
In APEX, the only way I got this to work is by specifying the URL in text...
 
Code:
PageReference lPr = new PageReference('/a0F/e—CF00N30000002qbnG='+EncodingUtil.urlEncode(this.lCase.Account.Name,'UTF-8')+'&CF00N30000002qbnG_lkid='+EncodingUtil.urlEncode(this.lCase.AccountId,'UTF-8')+'&saveURL='+EncodingUtil.urlEncode('/apex/CaseClusters–id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'),'UTF-8')+'&retURL='+EncodingUtil.urlEncode('/apex/CaseClusters˜id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'),'UTF-8'));
This does not migrate well from developement to production environment. But it works once the URL has been adapted to the target environment.
 
I did find some example related to the StandardController class that looked promissing, but did not work as expected. This will open the "case" record, not the "Cluster__c" object I intended it to.
 
Code:
Cluster__c theNewCluster = new Cluster__c(Account__c = this.lCase.AccountId);

PageReference lPr = (new ApexPages.StandardController(theNewCluster)).edit();

Is there a better way to handle this in APEX code, where the URLs are created dynamically, environment independent?

Any input would be greatly appreciated.

 
 
jeffdonthemicjeffdonthemic
Try having the method simply return the following:

Code:
return (new ApexPages.StandardController(theNewCluster)).edit();

Jeff Douglas
Informa Plc
blog.jeffdouglas.com

gribisgribis
Returning the PageReference directly per your suggestion does not change the behavior. We still are directed to the Case record instead of the new Cluster record.
jeffdonthemicjeffdonthemic
Can you post your controller's code?
 
Thanks
 
Jeff Douglas
Informa Plc
blog.jeffdouglas.com
gribisgribis
Note that this is an extension controller
Code:
public class extCaseClusters {
 public string CurrentAction;
 public Case lCase;
 public List<ClusterSelect> ClusterSelects;

 public String newUrl;
 public String setUrl(string pInit){
  this.newUrl = pInit;
  return this.newUrl;
 }

 public Map<Id, Case_Clusters__c> CaseClusters {
  public get{
   if (CaseClusters==null) {
          List<Case_Clusters__c> lClusters = [select cluster__r.Name, cluster__c, Case__c,Id from Case_Clusters__c where case__c =: this.lCase.Id order by cluster__r.Name];
          this.CaseClusters = new Map<Id, Case_Clusters__c>();
          for(Case_Clusters__c cc : lClusters) {
           if (cc.Cluster__c!=null)
           CaseClusters.put(cc.Cluster__c,cc );
          }
          //return CaseClusters;
   } 
   return CaseClusters;
  } private set;
 }
 
 public Set<Id> SelectedClusterIds { 
  get {
   Set <Id> SelectedClusterIds = new Set<Id>();
   SelectedClusterIds = CaseClusters.keySet();
   return SelectedClusterIds;
  }
 }
 
 public extCaseClusters(ApexPages.StandardController controller) {
  Case lTmpCase = (Case)controller.getRecord();
  // Retrieve all necessary attributes
  if (lTmpCase!=null) {
   this.lCase = [select ID, Account.ClusterCount__c, Account.Name, AccountId, Cluster__c, Cluster__r.Name from Case where ID=:lTmpCase.Id limit 1];
  }
  this.CurrentAction = ApexPages.currentPage().getParameters().get('a');
 }

   public ApexPages.StandardSetController setCon {
        get {
           if(setCon == null) {
             //List<Case_Clusters__c> lClusters = [select cluster__c, Id from Case_Clusters__c where case__c =: this.lCase.Id order by cluster__r.Name];
             //List<Id> lClusterIds = new List<Id>{};
             //for(Case_Clusters__c cc : lClusters) {
             // lClusterIds.add(lClusters.cluster__c);
             //}
    setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
    [select Id, Name, Location__c, Federation__c, Release__c, Release__r.Name, Primary_Contact__c, Leader_Node__c from Cluster__c Where Account__c=:this.lCase.AccountId or Id in : SelectedClusterIds]));               
            }
           return setCon;
          }
        set;
   }  
 
 public Id AddedId {
  public get {
   if (AddedId==null) {
    AddedId = (Id)ApexPages.currentPage().getParameters().get('newid');
   }
   return AddedId;
  } private set;
 }

 public List<ClusterSelect> getClusterSelects() {
     // Add new cluster if one was created
     String newId = ApexPages.currentPage().getParameters().get('newid');
  if(ClusterSelects == null) {
         ClusterSelects = new List<ClusterSelect>();
         List<Cluster__c> Clusters = (List<Cluster__c>) setCon.getRecords();
         for(Cluster__c c:Clusters) {
             ClusterSelect cs = new ClusterSelect(c, (CaseClusters.containsKey(c.Id) || this.AddedId==c.Id));
             ClusterSelects.add(cs);                   
         }
     }
     return ClusterSelects;
 }
   
    public class ClusterSelect {
        public Cluster__c cc { get; private set; }
        public boolean selected { get; set; }
       
        public ClusterSelect(Cluster__c c, boolean IsSelected) {
            this.cc = c;
            this.selected = IsSelected;
        }
    }

   
    public PageReference saveClusters() {
     // Locate cluster to add/drop
     List<Case_Clusters__c> lAddLinks = new List<Case_Clusters__c>{};
     List<Id> lDropLinks = new List<Id>{};
     for (ClusterSelect cs: ClusterSelects) {
      if (cs.selected) {
       // Add if necessary
       if (!CaseClusters.containsKey(cs.cc.Id)) {
        Case_Clusters__c lCl = new Case_Clusters__c();
        lCl.Cluster__c = cs.cc.Id;
        lCl.Case__c = this.lCase.Id;
        lAddLinks.add(lCl);
       }
      } else {
       if (CaseClusters.containsKey(cs.cc.Id)) {
        // Drop if necessary
        lDropLinks.add(CaseClusters.get(cs.cc.Id).Id);
       }
      }
     }
     // Perform add
     if (lAddLinks.size()>0) {
      insert lAddLinks;
     }
     // Perform drop
     if (lDropLinks.size()>0) {
      List<Case_Clusters__c> lDropLinksCC = [select Id from Case_Clusters__c where Id in : lDropLinks];
      delete lDropLinksCC;
     }
     // Redirect to primary Cluster case assignment page
        //PageReference lPr = new PageReference('/'+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'));
        PageReference lPr = new PageReference('/apex/CaseCluster—id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'));
        lPr.setRedirect(true);
        return lPr;
    }
    
    public PageReference cancel() {
        PageReference lPr = new PageReference('/'+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'));
        lPr.setRedirect(true);
        return lPr;
    } 
    public PageReference createNew(){
        PageReference lPr = new PageReference('/a0F/e–CF00N30000002qbnG='+EncodingUtil.urlEncode(this.lCase.Account.Name,'UTF-8')+'&CF00N30000002qbnG_lkid='+EncodingUtil.urlEncode(this.lCase.AccountId,'UTF-8')+'&saveURL='+EncodingUtil.urlEncode('/apex/CaseClusters˜id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'),'UTF-8')+'&retURL='+EncodingUtil.urlEncode('/apex/CaseClusters™id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'),'UTF-8'));
        lPr.setRedirect(true);
        return lPr;
    }
    
    public boolean CaseHasValidCluster{
     get { return (this.lCase.AccountId!=null) ;}
    }
        
    public PageReference validateCaseAccount(){
     PageReference lPr = null;
     if (this.CaseHasValidCluster) {
      
      if(this.AccountClusterCount == 0) {
          lPr = new PageReference('/a0F/e?CF00N30000002qbnG='+EncodingUtil.urlEncode(this.lCase.Account.Name,'UTF-8')+'&CF00N30000002qbnG_lkid='+EncodingUtil.urlEncode(this.lCase.AccountId,'UTF-8')+'&saveURL='+EncodingUtil.urlEncode('/apex/CaseClusters?id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'),'UTF-8')+'&retURL='+EncodingUtil.urlEncode('/apex/CaseClusters?id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'),'UTF-8'));
          lPr.setRedirect(true);
      }
     }
        return lPr;
    }
    
    public integer AccountClusterCount {
     get {
   if (AccountClusterCount==null) {
    AccountClusterCount = [select count() from Cluster__c Where Account__c=:this.lCase.AccountId or Id in : SelectedClusterIds];
   }
   return AccountClusterCount;      
     }
     set;
    }

    // Return currently selected clusters
 public List<SelectOption> getCaseClustersSelect() {
  List<SelectOption> options = new List<SelectOption>();
  List<Case_Clusters__c> cc = this.CaseClusters.Values();
  for (Case_Clusters__c c:cc) {
   options.add(new SelectOption(c.Cluster__c,c.cluster__r.Name));
  }
  return options;
 }
 // Case primary cluster attribute
 public Id primaryCaseCluster {
  get {
   if (primaryCaseCluster==null) {
    primaryCaseCluster = this.lCase.Cluster__c;
   }
   return primaryCaseCluster;
  }
  set;
 }
 
 public PageReference savePrimaryCluster() {
  if (this.primaryCaseCluster != this.lCase.Cluster__c) {
   this.lCase.Cluster__c = this.primaryCaseCluster;
   update this.lCase;
  }
     // Redirect to primary Cluster case assignment page
        PageReference lPr = new PageReference('/'+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'));
        lPr.setRedirect(true);
        return lPr; 
 }
 
    public PageReference editClusters(){
        PageReference lPr = new PageReference('/apex/CaseClusters?Id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'));
        lPr.setRedirect(true);
        return lPr;
    }
    
    public PageReference validatePrimaryCluster() {
     PageReference lPr = null;
     integer selectedClusterCount = this.CaseClusters.size();
     if (selectedClusterCount==0) {
      // If no clusters are available for account, create a cluster, otherwise go to cluste selection
      //integer AccountClusterCount = [select count() from Cluster__c Where Account__c=:this.lCase.AccountId or Id in : SelectedClusterIds];
      if (AccountClusterCount > 0) {
          lPr = new PageReference('/apex/CaseClusters?Id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'));
      } else {
          lPr = new PageReference('/a0F/e?CF00N30000002qbnG='+EncodingUtil.urlEncode(this.lCase.Account.Name,'UTF-8')+'&CF00N30000002qbnG_lkid='+EncodingUtil.urlEncode(this.lCase.AccountId,'UTF-8')+'&saveURL='+EncodingUtil.urlEncode('/apex/CaseClusters?id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'),'UTF-8')+'&retURL='+EncodingUtil.urlEncode('/apex/CaseClusters?id='+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'),'UTF-8'));
         }
         lPr.setRedirect(true);
     } else if (selectedClusterCount==1) {
      Case_Clusters__c c = this.CaseClusters.Values()[0];
      // If the primary case cluster is different from the avaiable cluster, change the primary on the case
      if (c.Cluster__c != this.lCase.Cluster__c) {
       this.lCase.Cluster__c = c.Cluster__c;
       update this.lCase; 
      }
      // in either case go back to case
      lPr = new PageReference('/'+EncodingUtil.urlEncode(this.lCase.Id,'UTF-8'));
      lPr.setRedirect(true);
     }
     return lPr;
    }
 
 // Test this object
    static testMethod void testCaseClusters() {
        // Test registration creation
        // Create an account
        Account a = new Account();
        a.Name = 'Test Cluster Account';
        insert a;
        //Create a contact
        Contact c = new Contact();
        c.AccountId = a.Id;
        c.FirstName = 'John';
        c.LastName = 'Doe'; 
        insert c;
        // Create a case
        Case theCase = new Case();
        theCase.AccountId = a.Id;
        theCase.Subject = 'Testing clusters';
        theCase.contactid = c.id;
        insert theCase;
        
  // Check validity before cluster exists for account
        ApexPages.StandardController sc = new ApexPages.StandardController(theCase);
        extCaseClusters cc = new extCaseClusters(sc);
  cc.validatePrimaryCluster();
  
        // Create a cluster
        Cluster__c theCLuster = new Cluster__c();
        theCluster.Name = 'New Prod Cluster';
        theCluster.account__c = a.Id;
        insert theCluster;
        
  // Check validity after cluster exists for account
  cc.validatePrimaryCluster();
        // Reset the session
        cc = null;
        sc = null;
        
        // Start the extension page
        sc = new ApexPages.StandardController(theCase);
        cc = new extCaseClusters(sc);
        // Set the cluster new ID
        ApexPages.currentPage().getParameters().put('newid',(String)theCluster.Id);
        // Get the list of clusters for account
        List<ClusterSelect> csel = cc.getClusterSelects();
        System.assertEquals(csel[0].selected,true);
        // Save the case cluster record, adding a case cluster record
        PageReference pr = cc.saveClusters();
        
        // Check primaryPage Validity - assign current Cluster to case details
        cc.validatePrimaryCluster();
        // Save the case cluster record, deleting a case cluster record
        csel[0].selected = false;
        System.assertNotEquals(csel[0].selected,true);
        pr = cc.saveClusters();
  // Test misc. actions
        pr = cc.cancel();
        pr = cc.createNew();
        pr = cc.editClusters();
        
        // Add a second cluster
        // Create a cluster
        Cluster__c theCLuster2 = new Cluster__c();
        theCluster2.Name = 'New Prod Cluster 2';
        theCluster2.account__c = a.Id;
        insert theCluster2;
        
        sc = new ApexPages.StandardController(theCase);
        cc = new extCaseClusters(sc);
        csel = cc.getClusterSelects();
        for (ClusterSelect cSelItem : cSel) {
         cSelItem.selected = true;
        }
        pr = cc.saveClusters();
        // Now do the primary cluster tests
        List<SelectOption> scs = cc.getCaseClustersSelect();
        cc.primaryCaseCluster =  theCluster2.Id;
        pr = cc.savePrimaryCluster();
        pr = cc.validateCaseAccount();
        
        // test the delete trigger for Case_Clusters
        delete theCluster2;
        
    }

}

Here is the related VF page code:

Code:
<apex:page standardController="case" extensions="extCaseClusters" action="{!validateCaseAccount}">
<apex:sectionHeader title="Case {!Case.CaseNumber}" subtitle="Select the primary clusters for the case" description="Case Subject: {!Case.Subject}" />
 <apex:form id="theForm">
 <apex:pageBlock rendered="{!(!CaseHasValidCluster)}">
 <apex:pageBlockSection columns="4">   
 The case does not have an account assigned. Please assign an account before editing the related clusters.
   </apex:pageBlockSection>
 </apex:pageBlock>
 <apex:pageBlock rendered="{!CaseHasValidCluster}">
 <apex:pageBlockButtons >
     <apex:commandButton action="{!saveClusters}" value="Save" />
     <apex:commandButton action="{!cancel}" value="Cancel" />
     <apex:commandButton action="{!createNew}" value="Create New Cluster" />
   </apex:pageBlockButtons>
   <apex:pageBlockTable value="{!ClusterSelects}" var="s" id="list">
    <apex:column ><apex:facet name="header">Select</apex:facet><apex:inputCheckbox value="{!s.selected}" /></apex:column>
    <apex:column ><apex:facet name="header">Reference</apex:facet><apex:outputLink value="/{!s.cc.Id}">{!s.cc.Name}</apex:outputLink></apex:column>
    <apex:column ><apex:facet name="header">Location</apex:facet><apex:outputLink value="/{!s.cc.Id}">{!s.cc.Location__c}</apex:outputLink></apex:column>
    <apex:column ><apex:facet name="header">Release</apex:facet><apex:outputfield value="{!s.cc.Release__c}" /></apex:column>
    <apex:column ><apex:facet name="header">Leader Node</apex:facet><apex:outputLink value="/{!s.cc.Id}">{!s.cc.Leader_Node__c}</apex:outputLink></apex:column>
    <apex:column ><apex:facet name="header">Federation</apex:facet><apex:inputCheckbox disabled="true" value="{!s.cc.Federation__c}" /></apex:column>
    <apex:column ><apex:facet name="header">Primary Contact</apex:facet><apex:outputField value="{!s.cc.Primary_Contact__c}" /></apex:column>
   </apex:pageBlockTable>
   <apex:panelGrid columns="5">
    <apex:commandLink action="{!setCon.previous}">Previous</apex:commandlink>
     <apex:commandLink action="{!setCon.next}">Next</apex:commandlink>
   </apex:panelGrid>
 </apex:pageBlock>
  </apex:form>
</apex:page>

This may be more than you asked for...
 
The "createNew" action is the element that I was experimenting with. The controller code has the working URL reference in it. What I tried was the following code without success:

Code:
    public PageReference createNew(){
     Cluster__c theNewCluster = new Cluster__c();
     theNewCluster.Account__c = this.lCase.AccountId;
     return (new ApexPages.StandardController(theNewCluster)).edit();
    }


 

 

rcravenrcraven
Did you ever get this to work, and if so please advise?