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
Luke@TWSLuke@TWS 

Best way to conditionally display a page

I have an page for an object which should always have a record. If it does not have a record then I want to create a new one using a vf page.

What would be the best way to do this?

Thought about checking for the existance of the record and then redirecting them to the other page if it does not exist, but not sure how to do this. Could also have two page sections, one displays if there is a record present and one if not, but would this be the best way?
David VPDavid VP
In your controller :

1) define a variable with the type of the record (private MyObject__c myObj { get; set; } )
2) in the controller's constructor query for  List<MyObject__c> obs = [select ..... ] ;
3) if the query returns one or more records set myObj = obs[0] ( ...or obs[1] ... )
4) if it doesn't return any records just instantiate a fresh new copy : myObj = new MyObject__c();
5) bind all your fields in the VF page to myObj


So, just one page that will allow you to fill in a new copy or show you the values of an already existing one.
wouldn't that work ?


David
Luke@TWSLuke@TWS
Different fields are required on the New page to the Edit page. Basically we take additional details on the New page, call a webservice and generate them a key. The key is used in the creation of the new record which you can edit along with a whole host of other thing on the Edit page. It would be the same as having a registration page.
David VPDavid VP
Ok, got it.


then you have some other options :

1) Put it all in one page and with the 'rendered' attributes separately render the 'new' or 'edit' sections (not my favorite)

2) Create different VF pages for new and edit functionality. In the 'action' attribute you can call a method which does the necessary checks for you and keeps you on one page or redirects you to the other one when necessary - the method just needs to return a new PageReference to send you to the other page or null to keep you on the same page.

I don't know if this is the 'best' way to do it (and there are more options to choose from) but I'd at least go for separate pages because in the long run it'll be probably easier to maintain them.



David
Brendan LallyBrendan Lally
in 2) u can also use components 2 use 'common code' and pass new/edit to that
Luke@TWSLuke@TWS
Thanks for suggestions. I will try the seperate page approach for now