Here I am trying to insert a Record. I have 2 input Field on the Form.when I click on the save Button,it just calling a JavaScript function:js(). This javaScript function take form inputField values, then check type is Prospect or not.If Type is Prospect then, Js function calling controller class method "insertRec" through apex actionFunction Tag.Now this insertRec method is a type of pageReference. This method will do 2 things. First, it inserts a record and while inserting if any errors occur then it add the Error message. second after insertion is complete it will redirect to the detail page of the newly created record.
Where i am going wrong with this code?
Below is my code:
VisualForce code
<apex:page id="Pg" controller="ActionFunctionController">
<script type="text/javascript" >
function js(){
var aname= document.getElementById("{!$component.FM.PB.PBS.actName}").value;
var aType = document.getElementById("{!$component.FM.PB.PBS.actType}").value;
if(aType!='Prospect'){
alert('You must Enter Prospect, to get your record save in DB');
}
else{
alert('New Record is going to insert');
/*Below Method is generated by "apex:actionFunction" which will call controller class Method "insertRec" */
insertAccount();
}
}
</script>
<apex:form id="FM">
<apex:actionFunction name="insertAccount" action="{!insertRec}" reRender="PB"/>
<apex:pageBlock id="PB">
<apex:pageMessages />
<apex:pageBlockSection id="PBS">
<apex:inputField value="{!acct.Name}" id="actName"/>
<apex:inputField value="{!acct.Type}" id="actType"/>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton value="save" onclick="js();"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex code
public class ActionFunctionController {
// Custom Controller
public Account acct{get;set;}
PageReference page;
public ActionFunctionController(){
Account acct = new Account();
}
public PageReference insertRec(){
// Logic
// Move to any mentioned page
if(acct.Name!=''){
insert acct;
}
else{
//Add Error mesaage to Apexpage class
Apexpages.Message msg = new Apexpages.Message(ApexPages.Severity.ERROR,'Insert failed');
ApexPages.addMessage(msg);
}
if(acct.id !=null){
// Send the user to the detail page for the new account.
PageReference page = new PageReference('/'+acct.id);
page.setRedirect(true);
}
return page;
}
}