You need to sign in to do that
Don't have an account?
Sudhir_Meru
Page is submitting after validation is checked from javascript
Hi,
I created a validation using javascript as mentioned below. I am calling this function on a button click as shown below.
Problem I am facing is function action="{!processSelected}"is getting called even if validation is throwing a alert message.
How to add condition action="{!processSelected}" must be called only if validation is passed. Please suggest.
Visual Force Button
<apex:pageBlockButtons id="reportbutton">
<apex:commandButton value="Save Records" action="{!processSelected}" onclick="Opportunity_Validation()"/>
</apex:pageBlockButtons>
Javascript
<script type="text/javascript">
function Opportunity_Validation()
{
var val = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.confignewopp.newopp}').value;
var oval = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.configopport.existopp}').value;
if ( val == '' && oval == '') {
alert('Enter Opportunity Details');
}
else if ( val != '' && oval != '') {
alert('Enter either existing opportunity or new opporutnity');
}
}
</script>
Thanks
Sudhir
I created a validation using javascript as mentioned below. I am calling this function on a button click as shown below.
Problem I am facing is function action="{!processSelected}"is getting called even if validation is throwing a alert message.
How to add condition action="{!processSelected}" must be called only if validation is passed. Please suggest.
Visual Force Button
<apex:pageBlockButtons id="reportbutton">
<apex:commandButton value="Save Records" action="{!processSelected}" onclick="Opportunity_Validation()"/>
</apex:pageBlockButtons>
Javascript
<script type="text/javascript">
function Opportunity_Validation()
{
var val = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.confignewopp.newopp}').value;
var oval = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.configopport.existopp}').value;
if ( val == '' && oval == '') {
alert('Enter Opportunity Details');
}
else if ( val != '' && oval != '') {
alert('Enter either existing opportunity or new opporutnity');
}
}
</script>
Thanks
Sudhir
<apex:commandButton value="Save Records" action="{!processSelected}" onclick="return Opportunity_Validation();"/>
All Answers
I tried still action is happening do you want see the controller code?
Thanks
Sudhir
you should return false from your javascript method when the validation fails. this will keep the control being passed to the server side.
also you should include return when calling the javascript method in the onclick event..
Visual Force Button
<apex:pageBlockButtons id="reportbutton">
<apex:commandButton value="Save Records" action="{!processSelected}" onclick="return Opportunity_Validation();"/>
</apex:pageBlockButtons>
Javascript
<script type="text/javascript">
function Opportunity_Validation()
{
var val = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.confignewopp.newopp}').value;
var oval = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.configopport.existopp}').value;
if ( val == '' && oval == '') {
alert('Enter Opportunity Details');
return false;
}
else if ( val != '' && oval != '') {
alert('Enter either existing opportunity or new opporutnity');
return false;
}
return true;
}
</script>
Hi Vamsi,
Still action is happening. data is getting insert from the function i am calling from the button.
I have highlited the function in below controller which is getting called from button. Please check
Controller
public with sharing class CCW_ContactPaginationController {
//URL Passing Parameters.
String PageContractId = ApexPages.currentPage().getParameters().get('ContractId');
String PageAccountId = ApexPages.currentPage().getParameters().get('AccountId');
public Asset GetAccount{get;set;}
public Asset GetContract{get;set;}
public Asset GetExpireDate{get;set;}
public Asset GetReseller{get;set;}
public Asset GetDistributor{get;set;}
public Boolean IncumbentReseller{get;set;}
public Boolean Education{get;set;}
public Asset GetOpportunity{get;set;}
public Asset GetNewOpportunity{get;set;}
public String ExpireTerms{get;set;}
//Our collection to class/wrapper objects wrapAsset
public List<CCWRowItem> wrapAssetList {get; set;}
public List<Asset> selectedAssets{get;set;}
/*
* item in context from the page
*/
public String contextItem{get;set;}
/*
* set controller
*/
private ApexPages.StandardSetController setCon;
/*
* the contact ids selected by the user
*/
private Set<Id> selectedContactIds;
/*
* constructor
*/
public CCW_ContactPaginationController ()
{
GetAccount = new Asset(); //Get Account Id from Page
GetContract = new Asset(); //Get Contract Name from Page
GetExpireDate = new Asset(); // Date Picker
GetReseller = new Asset();
GetDistributor = new Asset();
GetOpportunity = new Asset(); // Get Opportunity Id
GetNewOpportunity = new Asset(); // Get New Opportunity Name
fetch_data();
}
// public List<Asset> Asset_yourObjList{get;set;}
public void fetch_data ()
{
//init variable
this.selectedContactIds= new Set<Id>();
//gather data set
If ( GetAccount.AccountId == NULL || GetContract.Name == NULL )
{
If ( PageContractId <> NULL )
{
Contract C;
C = [SELECT Name FROM Contract WHERE Id = :PageContractId Limit 1];
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE last_contract_number__c = :C.Name Order by Service_End_Date_Max__c Desc Limit 1000] );
}
else If ( PageAccountId <> NULL )
{
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE AccountId = :PageAccountId Order by Service_End_Date_Max__c Desc Limit 1000] );
}
}
If ( GetAccount.AccountId <> NULL && GetContract.Name == NULL )
{
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE AccountId = :GetAccount.AccountId Order by Service_End_Date_Max__c Desc Limit 1000] );
}
Else If ( GetContract.Name <> NULL && GetAccount.AccountId == NULL )
{
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE last_contract_number__c = :GetContract.Name Order by Service_End_Date_Max__c Desc Limit 1000] );
}
Else If ( GetAccount.AccountId <> NULL && GetContract.Name <> NULL )
{
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE AccountId = :GetAccount.AccountId and last_contract_number__c = :GetContract.Name Order by Service_End_Date_Max__c Desc Limit 1000] );
}
this.setCon.setpageNumber(1);
this.setCon.setPageSize(10);
}
/*
* handle item selected
*/
public void doSelectItem(){
this.selectedContactIds.add(this.contextItem);
}
/*
* handle item deselected
*/
public void doDeselectItem(){
this.selectedContactIds.remove(this.contextItem);
}
/*
* return count of selected items
*/
public Integer getSelectedCount(){
return this.selectedContactIds.size();
}
/*
* advance to next page
*/
public void doNext(){
if(this.setCon.getHasNext())
this.setCon.next();
}
/*
* advance to previous page
*/
public void doPrevious(){
if(this.setCon.getHasPrevious())
this.setCon.previous();
}
//public List<CCWRowItem> rows = new List<CCWRowItem>();
public List<CCWRowItem> rows {get; set;}
/*
* return current page of groups
*/
public List<CCWRowItem> getContacts(){
rows = new List<CCWRowItem>();
for(sObject r : this.setCon.getRecords()){
Asset c = (Asset)r;
CCWRowItem row = new CCWRowItem(c);
if(this.selectedContactIds.contains(c.Id)){
row.IsSelected=true;
}
else{
row.IsSelected=false;
}
rows.add(row);
}
return rows;
}
// Store Selected Records to Object/Table
public void processSelected() {
Integer currentPageNumber = setCon.getPageNumber();
selectedAssets = new List<Asset>();
list<Temp_Assets__c> TempAssetList = new list<Temp_Assets__c>();
/* for(CCWRowItem wrapAssetObj : rows ) {
if(wrapAssetObj.IsSelected == true) {
selectedAssets.add(wrapAssetObj.tContact);
}
} */
setCon.setpageNumber(1);
while(true){
List<Asset> TempAssetLists = (List<Asset>)setCon.getRecords();
for(Asset assetIns : TempAssetLists ) {
if(this.selectedContactIds.contains(assetIns.Id)){
selectedAssets.add(assetIns);
}
}
if(setCon.getHasNext()){
setCon.next();
}
else{
break;
}
}
/**********Added by Unnat*********************************/
//below code should only execute if Expiry term has a value
Date maxDate=Date.valueOf('2000-1-1');
//Calculate the maximum Date off of the selected dates
//if (Expiry_term !=null {
//finds the latest expiry date out of the selected assets
for (Asset assets: selectedAssets) {
if(assets.Service_End_Date_Max__c > maxDate) {
maxDate=assets.Service_End_Date_Max__c;
}
}
//There will be another condition to add the expiry term to the latest expiry date
/*if (expiry_term== '1 Year') {
maxDate=maxDate.addYears(1).addDays(1);
}
else if (expiry_term == '3 Year') {
maxDate=maxDate.addYears(3).addDays(1);
}
else if (expirty_term == '5 Year') {
maxDate=maxDate.addYears(5).addDays(1);
}
}
else {
maxDate= expiry_date;
} */
/****************Completed by Unnat*****************************/
Account ResellerAct;
Account DistributorAct;
Opportunity Oppt;
for(Asset Act : selectedAssets)
{
Temp_Assets__c TempAsset = new Temp_Assets__c();
TempAsset.Name = 'Sudhir';
TempAsset.AccountId__c = Act.AccountId;
TempAsset.Product__c = Act.Product2Id;
TempAsset.Serial_Number__c = Act.SerialNumber;
TempAsset.Last_Contract_Number__c = Act.last_contract_number__c;
TempAsset.Service_Start_Date__c = Act.Service_Start_Date_Min__c;
TempAsset.Service_End_Date__c = Act.Service_End_Date_Max__c;
//TempAsset.Service_End_Date__c = maxDate;
TempAsset.Install_Date__c = Act.InstallDate;
If (GetReseller.AccountId <> NULL)
{
ResellerAct = [ SELECT Id FROM Account WHERE ID = :GetReseller.AccountId Limit 1];
TempAsset.Reseller__c = ResellerAct.Id;
}
If (GetDistributor.AccountId <> NULL )
{
DistributorAct = [ SELECT Id FROM Account WHERE ID = :GetDistributor.AccountId Limit 1];
TempAsset.Distributor__c = DistributorAct.Id;
}
If ( GetOpportunity.Opportunity__c <> NULL )
{
Oppt = [SELECT Id FROM Opportunity WHERE ID = :GetOpportunity.Opportunity__c Limit 1];
TempAsset.Existing_Opportunity__c = Oppt.Id;
}
TempAsset.Incumbent_Reseller__c = IncumbentReseller;
TempAsset.Education__c = Education;
TempAsset.Expiry_Date__c = GetExpireDate.Expire_Date__c;
TempAsset.New_Opportunity__c = GetNewOpportunity.New_Opportunity__c;
TempAsset.Expiry_Term__c = ExpireTerms;
//Add the selected Assets to the List
TempAssetList.add(TempAsset);
}
Insert TempAssetList;
setCon.setpageNumber(currentPageNumber);
}
/*
* return whether previous page exists
*/
public Boolean getHasPrevious(){
return this.setCon.getHasPrevious();
}
/*
* return whether next page exists
*/
public Boolean getHasNext(){
return this.setCon.getHasNext();
}
/*
* return page number
*/
public Integer getPageNumber(){
return this.setCon.getPageNumber();
}
/*
* return total pages
*/
Public Integer getTotalPages(){
Decimal totalSize = this.setCon.getResultSize();
Decimal pageSize = this.setCon.getPageSize();
Decimal pages = totalSize/pageSize;
return (Integer)pages.round(System.RoundingMode.CEILING);
}
/*
* helper class that represents a row
*/
public with sharing class CCWRowItem{
public Asset tContact{get;set;}
public Boolean IsSelected{get;set;}
public CCWRowItem(Asset c){
this.tContact=c;
this.IsSelected=false;
}
}
}
Thanks
Sudhir
I have higligthted the code. Please check below
<apex:page controller="CCW_ContactPaginationController" showHeader="false" sidebar="false" readOnly="false" cache="false">
<script type="text/javascript">
/*
* function to handle checkbox selection
*/
function doCheckboxChange(cb,itemId){
if(cb.checked==true){
aSelectItem(itemId);
}
else{
aDeselectItem(itemId);
}
}
</script>
<script type="text/javascript">
function Opportunity_Validation()
{
var val = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.confignewopp.newopp}').value;
var oval = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.configopport.existopp}').value;
var eterm = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.configexpire.expterms.exptermsnon}').value;
var edate = document.getElementById('{!$Component.RenewalForm.configblock.configsecblock.configexpiredate.expredate}').value;
if ( val == '' && oval == '') {
alert('Enter Opportunity Details');
return false;
}
else if ( val != '' && oval != '') {
alert('Enter either existing opportunity or new opporutnity');
return false;
}
else if ( edate == '' ) {
alert('Expire Date is null');
return false;
}
return true;
}
</script>
<apex:sectionHeader subtitle="Create Renewal Quote" title="Meru Networks"/>
<apex:form id="RenewalForm">
<apex:pageBlock id="filterblock">
<apex:pageBlockSection title="Filters" columns="3" id="filterblocksection">
<apex:inputField value="{!GetAccount.AccountId}" label="Account"/>
<apex:inputField value="{!GetContract.Name}" label="Contract" required="false"/>
<apex:commandButton action="{!fetch_data}" value="Fetch Data"></apex:commandbutton>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock id="reportblock">
<apex:pageBlockButtons id="reportbutton">
<apex:commandButton value="Save Records" action="{!processSelected}" onclick="Opportunity_Validation()"/>
<apex:commandButton value="Cancel" onclick="window.top.close()"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Install Base Report" id="mpb" collapsible="true" columns="1" >
<!-- handle selected item -->
<apex:actionFunction name="aSelectItem" action="{!doSelectItem}" rerender="mpb">
<apex:param name="contextItem" value="" assignTo="{!contextItem}"/>
</apex:actionFunction>
<!-- handle deselected item -->
<apex:actionFunction name="aDeselectItem" action="{!doDeselectItem}" rerender="mpb">
<apex:param name="contextItem" value="" assignTo="{!contextItem}"/>
</apex:actionFunction>
<!-- table of data -->
<apex:pageBlockTable title="Assets" value="{!Contacts}" var="c" id="reportblocktable">
<apex:column >
<apex:facet name="header">Action</apex:facet>
<apex:inputCheckbox value="{!c.IsSelected}" onchange="doCheckboxChange(this,'{!c.tContact.Id}')"/>
</apex:column>
<apex:column value="{!c.tContact.AccountId}"/>
<apex:column value="{!c.tContact.Product2Id}"/>
<apex:column value="{!c.tContact.SerialNumber}"/>
<apex:column value="{!c.tContact.last_contract_number__c}"/>
<apex:column value="{!c.tContact.Service_Start_Date_Min__c}"/>
<apex:column value="{!c.tContact.Service_End_Date_Max__c}"/>
<apex:column value="{!c.tContact.InstallDate}"/>
</apex:pageBlockTable>
<apex:pageBlockSection collapsible="false" columns="4" id="paginsecblock">
<!-- count of selected items -->
<apex:outputLabel value="[{!selectedCount} records selected]" />
<apex:outputLabel value=" (page {!pageNumber} of {!totalPages}) " />
<!-- next, previous and page info -->
<apex:commandLink action="{!doPrevious}" rendered="{!hasPrevious}" value="Previous" />
<apex:outputLabel rendered="{!NOT(hasPrevious)}" value="Previous" />
<apex:commandLink action="{!doNext}" rendered="{!hasNext}" value="Next" />
<apex:outputLabel rendered="{!NOT(hasNext)}" value="Next" />
</apex:pageBlockSection>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock id="configblock">
<apex:pageBlockSection title="Configuration Option" columns="2" id="configsecblock">
<apex:pageBlockSectionItem id="configexpire">
<apex:outputLabel value="Expiry Term:" for="expireterm"/>
<apex:selectList value="{!ExpireTerms}" multiselect="false" size="1" id="expterms">
<apex:selectOption itemValue="0" itemLabel="--none--" id="exptermsnon"/>
<apex:selectOption itemValue="1" itemLabel="1 Year"/>
<apex:selectOption itemValue="3" itemLabel="3 Year"/>
<apex:selectOption itemValue="5" itemLabel="5 Year"/>
</apex:selectList>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="configexpiredate">
<apex:outputLabel value="Expiry Date:"/>
<apex:inputField value="{!GetExpireDate.Expire_Date__c}" id="expredate"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="configincumbent">
<apex:outputLabel value="Incumbent Reseller"></apex:outputLabel>
<apex:inputCheckbox value="{!IncumbentReseller}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="configeducation">
<apex:outputLabel value="Education"></apex:outputLabel>
<apex:inputCheckbox value="{!Education}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="configreseller">
<apex:outputLabel value="Reseller"></apex:outputLabel>
<apex:inputField value="{!GetReseller.AccountId}" required="true"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="configdistrbutor">
<apex:outputLabel value="Distributor"></apex:outputLabel>
<apex:inputField value="{!GetDistributor.AccountId}" required="true"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="configopport">
<apex:outputLabel value="Opportunity"></apex:outputLabel>
<apex:inputField value="{!GetOpportunity.Opportunity__c}" id="existopp"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="confignewopp">
<apex:outputLabel value="New Opportunity"></apex:outputLabel>
<apex:inputField value="{!GetNewOpportunity.New_Opportunity__c}" id="newopp"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
<apex:commandButton value="Save Records" action="{!processSelected}" onclick="return Opportunity_Validation();"/>