Thursday 23 March 2017

How to deal with Action function & Apex Command Button Together

I have seen many posts where I found newbies are struggling with issues when they call action function from apex:command button. 

I have some points to be considered: 
1. My first recommendation is to avoid calling action function from apex Command Button until unless you have specific requirement to validate some inputs in javascript before hitting the server. 

2. If you have to call action function from command button then please follow below points. 
     2.A) When you use action function and command button then you page gets submitted two times and it causes an issue of setting public properties (bound with Page like setters) to null value. 
     2.B) To resolve this issue use  "return false;" in your onclick event just after calling JS function or action function. 
    2.C) Please go through with below code to see how to do it. 

<apex:page Controller="myController">
<apex:form>
<apex:actionFunction action="{!SaveData}" name="SaveData" reRender="pbId" />
<script>
function Save() {                
SaveData();                                      
}
</script>
<apex:pageBlock id="pbId" >
<apex:commandButton value="Submit" onclick="Save(); return false;" rerender="pbId" />
</apex:form>
</apex:page>

How to check if at least one check box is selected in Apex Page BlockTable

Hi folks,

I would like to touch a very common scenario we had to check if at least item (from checkbox) is selected from a data table before submitting the form.

I have implemented it as below:

<apex:page Controller="myController">
<apex:includeScript value="{!URLFOR($Resource.jsFiles, 'jquery-1.7.1.min.js')}" />
<apex:includeScript value="{!URLFOR($Resource.JQueryUI, 'jquery-ui-1.11.2/jquery-ui.min.js')}"></apex:includeScript>
<script>
j$ = jQuery.noConflict();
function Save() {
                if(j$(".selectionCheckbox:checked").length == 0){
                          alert('Please select at least one Item.');
                       }
                       else {
                        // Call action function to go ahead to save
                       }                
                }
</script>
<apex:pageBlock id="pbId" >
<apex:pageBlockTable value="{!SampleDataList}" var="RelatedData">
<apex:column >
<apex:facet name="header">
<apex:inputCheckbox id="checkAll"
onClick="jQuery('.selectionCheckbox').attr('checked', this.checked);" />
</apex:facet>
<apex:inputCheckbox styleClass="selectionCheckbox"
id="myCheckbox" value="{!RelatedData.isSelected}" />
</apex:column>
<apex:column value="{!RelatedData.Name}" />
</apex:pageBlockTable>
</apex:pageBlockTable>
<apex:commandButton value="Save" onclick="Save(); return false;"
rerender="pbId" />
</apex:page>