I have javascript function in my salesforce page to validate if one of the contacts have open cases. This function calls an apex getter to get the value. The problem I`m facing is that the apex getter is always returning the wrong boolean. I tried debugging it, everything seems to work but for some reason the returned bool is wrong.
apex function:
public Boolean openCase{
get{
if (Contacts.size() > 0){
for(cContact wContact: dicContacts.values()){
if(wContact.selected){
if(wContact.con.account.Number_of_open_Financial_Review_Cases__c > 1){
return true;
}
}
}
return false;
}
set{}
}
js function:
function validateOpenCases(sendEmail){
doIt = true;
oc = {!openCase}; // <<== problem here
alert(oc);
if (oc)
{
doIt=confirm('blabla?');
}
if(doIt){
// do stuff
}
else{
// do nothing
}
}
You should not bind Apex objects/variables directly in JavaScript (like you have {!openCase};
). I've had many issues with this before. Instead use JavaScript Remoting or the Ajax Toolkit.
Another option is to use a hidden Visualforce input to store your bound Visualforce value. Then you can get that value in your JavaScript.
Here's an example:
<apex:page controller="myController">
<script>
function getInputEndingWith(endsWith)
{
// put together a new Regular Expression to match the
// end of the ID because Salesforce prepends parent IDs to
// all elements with IDs
var r = new RegExp("(.*)"+endsWith+"$");
// get all of the input elements
var inputs = document.getElementsByTagName('input');
// initialize a target
var target;
// for all of the inputs
for (var i = 0; i < inputs.length; ++i)
{
// if the ID of the input matches the
// Regular Expression (ends with)
if (r.test(inputs[i].id))
{
// set the target
target = inputs[i];
// break out of the loop because target
// was found
break;
}
}
// return the target element
return target;
}
function validateOpenCases(sendEmail)
{
doIt = true;
oc = getInputEndingWith("OpenCase").value;
alert(oc);
if (oc === "true") {
doIt = confirm('Are you sure?');
}
if (doIt) {
// do stuff
}
else {
// do nothing
}
}
</script>
<apex:form>
<apex:outputpanel>
<apex:inputhidden id="OpenCase" value="{!openCase}" />
</apex:outputpanel>
<input type="button" class="btn" onclick="validateOpenCases('Send');" value="Validate" />
</apex:form>
</apex:page>