+ Start a Discussion
GstartGstart 

How to pass two custom object records between vf pages using same custom controller?

These are my current setup
- 1 custom controller
- 2 vf pages using the same custom controller
- 2 custom objects where page 1 uses object 1 and page 2 uses object 2(User inputs data for object 1 in page 1 and object 2 in page 2)

My requirement is, I should be able to move back and forth between page 1 and 2, and I should be able to hold the data entered by the user when moving between pages. Note: The user haven't saved the data yet when moving between pages. 
 
public class customController{

public Object1__c object1{get;set;}

public Object2__c object2{get;set;}

public customController()
{
       Id id = ApexPages.currentPage().getParameters().get('id');

       this.object1=(id == null) ? new Object1__c () :[select field1__c,field2__c from Object1__c where Id=:id ];

       //will this work and is it correct??
       this.object2=(id == null) ? new Object2__c () [select field3__c,field4__c from Object2__c where Id=:id ];
}


I have shared a sample of the logic I have written to retrieve the data in the constructor. Apparently, this seems to work and the data is still available when moving between pages, but is this correct?(I am using a single variable "id" to retrieve data from last page for both objects) And I am unable to write a test class, because it fails in the constructor
Suraj PSuraj P
The values of object1 and object2 should be retained as you jump back and forth between the pages, as long as you don't use pagereference.setRedirect(true) in the controller method responsible for navigation between the 2 pages. If you're going to retrive the record for object1 or object2 in your constructor, you may want to do a pre-check to see which object the id belongs to:
 
if(id!=null && id.getSObjectType().getDescribe().getName()=='Object1'){
//retrieve object1 record
}else if(id!=null){
//retrieve object2 record
}

 
GstartGstart
If I put the if-else, the data I entered in page 1 is not available anymore when I navigate from page 2 to page 1.