Saturday 1 December 2012

Call JS function and Controller function together from a VF component


Sometimes we need to check values, data entered by the user or simply we validate the input data for better data quality. And after validation we like to go ahead to the database using DML.

It is advisible to use Java script for client side and then use your controller / class for rest of the logics.

This example will show you, how we can achieve both validation and controller from a single command button:


Controller:

 public class testClass{
public boolean renderVar {get;set;}
public string textValue {get;set;}
public testClass(){
renderVar= false;
}
public void showPanel(){
renderVar=true;
}
}



VF Page:

<apex:page controller="testClass">

<script type="text/javascript">
function jsFunction(){
var returnVal = confirm("Do you want to go to controller?");
return returnVal;
}
</script>

<apex:form>
<apex:outputPanel id="panelId" rendered={!renderVar}>
<apex:inputText id="text" value={!textValue} />
</apex:outputPanel>
       
         <!-- Below command button first calls onClick method and if it returns true then goes ahead        
         with action  attribute -->

<apex:commandButton value="Click Me" action="{!showPanel}" onClick = " if(!jsFunction()    
         {return false;} )"  reRencder="panelId">

</apex:form>
</apex:page>


Please note: onComplete attribute of command button component can also be used to do operations post controller action call.

No comments:

Post a Comment