How to implement "Save & New" functionality in a VisualForce Page - salesforce

I know that this is how to save a record
<apex:commandButton action="{!save}" value="Save"/>
Now I want a button to save the current record and reset the form to input another record.
Something like this...
<apex:commandButton action="{!SaveAndNew}" value="Save & New"/>

The URL for the new record page is the {org URL}/{3 letter object prefix}/e?".
You could define your save method as follows, where m_sc is a reference to the standardController passed to your extension in it's constructor:
public Pagereference doSaveAndNew()
{
SObject so = m_sc.getRecord();
upsert so;
string s = '/' + ('' + so.get('Id')).subString(0, 3) + '/e?';
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.Info, s));
return new Pagereference(s);
}
To use your controller as an extension, modify it's constructor to take a StandardController reference as an argument:
public class TimeSheetExtension
{
ApexPages.standardController m_sc = null;
public TimeSheetExtension(ApexPages.standardController sc)
{
m_sc = sc;
}
//etc.
Then just modify your <apex:page> tag in your page to reference it as an extension:
<apex:page standardController="Timesheet__c" extensions="TimeSheetExtension">
<apex:form >
<apex:pageMessages />
{!Timesheet__c.Name}
<apex:commandButton action="{!doCancel}" value="Cancel"/>
<apex:commandButton action="{!doSaveAndNew}" value="Save & New"/>
</apex:form>
</apex:page>
Note that you don't need Extension in the class name, I just did that to be sensible. You shouldn't need to modify anything else on your page to utilise this approach.

Ideally, you could use the ApexPages.Action class for this. But when I've tried to use it, it's been too buggy. It's been a while, so you might want to play with it using the {!URLFOR($Action.Account.New)} action.
What will work is simply using a PageReference to redirect the user to the "new" URL.
For example, if this were for Accounts,
public PageReference SaveAndNew() {
// code to do saving goes here
PageReference pageRef = new PageReference('/001/e');
return pageRef;
}

Related

Selecting picklist option on Visual force page upon load

I have a visualforce page that has a picklist called Topic and sometimes I will need to select one of the picklist options upon page load (meaning the Topic will be passed on from another page and will need to be selected upon loading the page for the first time). I'm not sure how to do this? I'm posting part of the Visualforce page that handles topic selection and the Controller code that below. Any help would be appreciated.Thanks.
Visualforce page:
<!---------------------------------- Select Topic ----------------------------------------------------->
<apex:pageblockSection title="Select the Topic" >
<apex:selectList value="{!topic}" size="1">
<apex:outputlabel for="Topic" value="Pick a Topic :" ></apex:outputlabel>
<apex:selectOptions id="topic" value="{!Topics}"/>
<apex:actionSupport action="{!populateParameters}" reRender="parametersSection,querySection" event="onchange"/>
</apex:selectList>
</apex:pageblockSection>
<!---------------------------------- End of Select Topic ---------------------------->
<!---------------------------------- Parameters for Topic ----------------------------------------------------->
<apex:pageblockSection id="parametersSection" title="Input Parameters">
<apex:repeat value="{!topicpParamWrapperList}" var="params">
<apex:outputPanel >
<apex:outputlabel value="{!params.parameter.Name}" ></apex:outputlabel>
<apex:inputfield value="{!params.parameter.inputValue__c}" rendered="{!params.renderAsText}">
<apex:actionsupport action="{!placeValuesInQuery}" reRender="querySection,splunUrlLink" event="onchange"/>
</apex:inputfield>
<apex:inputfield value="{!params.parameter.DateTimeValueHolder__c}" rendered="{!params.renderAsDate}">
<apex:actionsupport action="{!placeValuesInQuery}" reRender="querySection,splunUrlLink" event="onchange"/>
</apex:inputfield>
</apex:outputPanel>
</apex:repeat>
</apex:pageblockSection>
<!---------------------------------- End of Parameters for Topic ----------------------------------------------------->
Apex Controller
public List < topicpParamWrapper > topicpParamWrapperList {
get;
set;
} {
topicpParamWrapperList = new List < topicpParamWrapper >();
}
public void populateParameters()
{
if(!topicpParamWrapperList.isEmpty())
{
topicpParamWrapperList.clear();
}
if(topic!='' && topic!=Null)
{
for(Query_Parameter__c qParam :[select id, Parameters__r.Variable_Name__c, Parameters__r.Type__c,Parameters__r.Name from Query_Parameter__c where Topics__c=:topic])
{
Parameters__c param = new Parameters__c();
param.Name =qParam.Parameters__r.Name ;
param.type__c = qParam.Parameters__r.type__c;
param.Variable_Name__c=qParam.Parameters__r.Variable_Name__c;
topicpParamWrapperList.add(new topicpParamWrapper(param));
}
getQueryToRun();
}
}
public void getqueryToRun(){
if(mapTopics.containsKey(topic))
{
this.queryToRun =mapTopics.get(topic).query__c;
this.queryMain=mapTopics.get(topic).query__c;
}
}
public List < topicpParamWrapper > paramList {
get;
set;
} {
paramList = new List <topicpParamWrapper>();
}
All you really have to do is to set the topic to some initial value in the constructor (the special function that has name identical to class' name). You set it to some value and then it'll be rendered properly in visualforce (assuming same value is one of the selectable options!).
You have omitted the constructor or <apex:page> tag so we don't know how you're navigating to that page. But probably easiest for you would be to pass the topic in the URL. So if you access the page like that:
/apex/MyPage?topic=Something, something
then in the constructor you could do this:
topic = ApexPages.currentPage().getParameters().get('topic');
(the name of the URL parameter doesn't have to be same as the variable name but it makes sense to have them at least similar)
You can read more about getParameters()
If there is risk that your topic will contain &, spaces etc you probably should URLENCODE it when building the link.

Invalid field Email for SObject AggregateResult in VisualForce

I want to display the AggregateResult on my Visualforce page but it is generating the following error " Invalid field Email for SObject AggregateResult"
Below is my code:
public with sharing class searchDuplicate {
public AggregateResult[] con{get;set;}
public searchDuplicate()
{
find();
}
public void find(){
con = [select Email from Contact group by Email having count(Email) > 1];
System.debug(con);
}
}
Below is my visualforce page code:
<apex:page controller="searchDuplicate">
<apex:pageBlock title="Searching for Duplicate Contacts Record">
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:dataTable value="{!con}" var="c" border="2" cellspacing="5" cellpadding="5">
<apex:column headerValue="Email" value="{!c['Email']}" />
</apex:dataTable>
</apex:pageBlock>
</apex:page>
kindly Make a correction if possible
public with sharing class searchDuplicate {
public list <con> conList{get;set;}
public class con{
public string Email {get;set;}
public con( string email){
this.Email = email;
}
}
public searchDuplicate()
{
find();
}
public void find(){
conList = new list <con>();
for( AggregateResult ar : [select Email from Contact group by Email having count(Email) > 1];){ conList.add(new con(string.valueOf(ar.get('Email')))) }
}
}
Aggregate results (and their fields/columns) come as generic Objects, not sObjects. Therefore there's no obj.get('somefieldname') you can call on them.
Your best option might be to make a helper class that has String email; Integer count; fields and loop through the query results populating a list of objects of this helper class.
You could also use Map<String, Integer> but that'd come to VF as not sorted alphabetically.
See https://salesforce.stackexchange.com/questions/7412/count-a-grouped-by-soql if you need a code sample.
Although the other answers are correct in solving your problem, what you have is actually a bug in SalesForce.
The way to resolve this without creating a custom object is to separate the into two - The "headerValue" and "value" both being set cause this error.
You want to change it to this:
<apex:dataTable value="{!con}" var="c" border="2" cellspacing="5" cellpadding="5">
<apex:column headerValue="Email" >
<apex:outputText>{!c['Email']}</apex:outputText>
</apex:column>
</apex:dataTable>
Thanks,
Michael

How can I pass variables state from one page to another, if both pages use the same controller, but the second page uses a controller extension?

I have a page that needs to pass data to another page. They both use the same controller, but the second page has its own controller extension. When the first page passes data to the second page, the second page will recall the constructor of the controller. If I remove the controller extension from the second page, data can be passed and the constructor is only called on the first page, not on the second.
How can I pass state from one page to another, if both pages use the same controller, but one page uses a controller extension?
For example, in the following code, if I enter data in the outputText for the variable t and then go to the next page, the state won't save, the constructor will be recalled, and the value for t on page 2 will be "construct". If the testExtension is removed from the second page, then everything works fine.
apex/test1
VisualForce
<apex:page controller="test">
<apex:outputText value="{!t}" />
<apex:commandButton action="/test2" value="Go to test2" />
</apex:page>
Controller
class test {
public String t {get; set;}
public test() {
t = 'construct';
}
}
apex/test2 VisaulForce
<apex:page controller="test" extension="testExtension">
<apex:outputLabel value="{!t}" />
</apex:page>
controller extension:
class testExtension {
public testExtension(test controller) {
}
}
public with sharing class Fake01_Controller {
public String fake02String {get;set;}
public PageReference fake03Submit() {
PageReference prToNavigate = null;
prToNavigate = Page.Fake_02;
return prToNavigate;
}
}
Fake 01 page:
<apex:form >
<apex:inputText value="{!fake02String}" />
<apex:commandButton action="{!fake03Submit}"
value="Navigate to Fake 02"
/>
</apex:form>
Fake 02 page:
<apex:form >
<apex:outputText value="{!fake02String}" />
</apex:form>
Please, read PageReference about setRedirect method:
If set to false, the redirect is a server-side forward that preserves
the view state if and only if the target page uses the same controller
and contains the proper subset of extensions used by the source page.
class test {
public String t {get; set;}
public test() {
t = 'construct';
}
public PageReference test2() {
return page.test2;
}
}
<apex:page controller="test">
<apex:outputText value="{!t}" />
<apex:commandButton action="{!test2)" value="Go to test2" />
</apex:page>

How can I link labels in a SelectCheckBoxes component in Visualforce?

I have an <apex:SelectCheckBoxes> component in my Visualforce page, which gets its select options from an Apex method. I want to have a label with a link appearing next to each checkbox. How can I achieve this? Please help.
One way to accomplish this is by using apex:inputCheckbox controls individually, rather than relying on selectCheckboxes to do all the rendering for you. It's hard to get more specific in a suggestion because the question can be answered in many ways.
If, for example, you need these checkboxes to appear in a list alongside SObject instances, create a wrapper class. If they are essentially a-la-carte, you can create a class that contains a Boolean and create a list of instances of this class. Then create a dataTable, pageBlockTable, etc., and in one of the columns you include the checkbox component. Or simply use apex:repeat if you don't want any of the other table formatting.
Here's the repeat example from the VF guide:
<!-- Page: -->
<apex:page controller="repeatCon" id="thePage">
<apex:repeat value="{!strings}" var="string" id="theRepeat">
<apex:outputText value="{!string}" id="theValue"/><br/>
</apex:repeat>
</apex:page>
/*** Controller: ***/
public class repeatCon
{
public String[] getStrings()
{
return new String[]{'ONE','TWO','THREE'};
}
}
Replacing outputText with inputCheckbox and a String array with Boolean. Then simply start with an apex:outputLink and follow it with the checkbox.
EDIT -
Here's an example of using a class to get the job you want done.
Apex:
public class Example
{
public List<CheckboxClass> theCheckboxes {get; private set;} // Reference THIS array
public Example()
{
theCheckboxes = new List<CheckboxClass>();
theCheckboxes.add(new Checkbox(true));
theCheckboxes.add(new Checkbox(false));
theCheckboxes.add(new Checkbox(true));
theCheckboxes.add(new Checkbox(false));
}
public class CheckboxClass
{
public Boolean theCheckbox {get; private set;}
public CheckboxClass(Boolean b)
{
this.theCheckbox = b;
}
}
}
Visualforce:
<apex:form>
<apex:pageBlock>
<apex:pageBlockTable value="{!theCheckboxes}" var="item">
<apex:column headerValue="The Checkboxes">
<apex:inputCheckbox value="{!item.theCheckbox}">
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
I haven't tested this, but this is the idea I believe you're looking for.

How to implement "Cancel" functionality in a VisualForce Page

I know that this is how to save a record
<apex:commandButton action="{!save}" value="Save"/>
I want a button to NOT save the current record (ie. Cancel) and navigate to the list of saved record (ie. list of objects for that object type).
Something like this...
<apex:commandButton action="{!cancel}" value="Cancel"/>
The list view for an object is your base URL / the 3 letter prefix for your object / o, for example:
https://na1.salesforce.com/a0C/o
So you could just create an action method that returns a Pagereference with the appropriate URL and set to redirect (pr.setRedirect(true)).
Alternatively, you could use your controller as an extension to a standard controller, and just call cancel on the standard controller:
// controller extension
public class TimeSheetExtension
{
ApexPages.standardController m_sc = null;
public TimeSheetExtension(ApexPages.standardController sc)
{
m_sc = sc;
}
public PageReference doCancel()
{
return m_sc.cancel();
}
}
// page
<apex:commandButton action="{!doCancel}" value="Cancel"/>
Note that this doesn't necessarily take you to the list view, it'll return you to the last page you were viewing before going to the VF page.
You should also add the immediate tag to your Cancel button, so that the form doesn't run any validation before performing the Cancel operation.
<apex:commandButton action="{!cancel}" immediate="true" value="Cancel"/>
See http://blogs.developerforce.com/developer-relations/2008/12/using-the-immediate-attribute-on-commandlinks-and-commandbuttons.html
While applying cancel operation visualforce you should stop the form validation.Use below any one methods to stop the form validation based on your requirements.
Method 1:
Using
html-5 in doctype in visualforce page
means you should use html-formnovalidate and immediate in cancel button. For example
<apex:commandButton action="{!cancel}" value="Cancel" immediate="true"
html-formnovalidate="formnovalidate" />
Method 2:
you should use immediate key word only need for stopping form validation. For Example
<apex:commandButton action="{!cancel}" value="Cancel" immediate="true"/>
One of the other answers suggested calling the standard controller's cancel action so I want to expand on that since it led me in the direction to solve my similar problem.
If you want to cancel an edit as an ajax request without refreshing the whole page, declare the action as void and don't return the page reference, but still call the 'cancel' action on the standard controll. Make sure the command button specifies the rerender attribute.
// controller extension
public class TimeSheetExtension
{
ApexPages.standardController m_sc = null;
public TimeSheetExtension(ApexPages.standardController sc)
{
m_sc = sc;
}
public void doCancel()
{
m_sc.cancel();
}
}
// page
<apex:commandButton action="{!doCancel}" value="Cancel" rerender="container_id"/>

Resources