Reputation: 863
I have a Date of Birth field and an age field in a CRM Form. When the record is saved the age is calculated and if the age is less than 18 the Age field should turn red.
When I save the form the field turns red for a second and then changes back to normal. My web resource is using OnSave event of the form. When I use the change color code on ONChange event of the Age field, I have to save the form twice to show that it turns red.
How do I get rid of this saving the form twice? Here is my code:
function setAge()
{
var DOB = Xrm.Page.getAttribute("inmate_dob").getValue();
var Today = Xrm.Page.getAttribute("inmate_bookingdate").getValue();
Today.setHours(0, 0, 0, 0);
var db = 0;
if(DOB > Today )
{
alert("Please Enter Genuine BirthDate !!!");
Xrm.Page.getAttribute("inmate_dob").setValue(null);
}
else
{
db = Today.getFullYear() - DOB.getFullYear();
var x = Today.getDate() ;
var y = DOB.getDate() ;
var a = Today.getMonth() + 1;
var b = DOB.getMonth() + 1;
if((a < b) || (a==b & x < y))
db=db - 1;
}
var result = Xrm.Page.getAttribute("inmate_age").setValue(db);
if (db <18)
{
document.getElementById("inmate_age").style.backgroundColor = 'red';
document.getElementById("inmate_age_c").style.backgroundColor = 'red';
}
}
}
I have also tried to use the last IF condition separately on ONChange event of Age field. This prompts me to save the record twice.
Upvotes: 1
Views: 3752
Reputation: 1146
I think that your specific error is related to the fact that after the save, the form is refreshed, losing the color that you set. You need to calculate it on the onLoad too.
Basically what happened is:
OnSave -> Calculate
Form refresh -> Lose the color
OnLoad -> you need to re-apply your script
Upvotes: 0
Reputation: 6715
Could you not calculate the field onChange?
e.g.
Xrm.Page.getAttribute('inmate_age').addOnChange(function() {
var theyAre18 = yourFunctionToCalculateIfTheyAre18OrNot();
if (theyAre18) {
//make the background white
}
else {
//make the background red
}
});
That way you could run it once onload and only change if the value changes. When you change the colour onSave, the form is going to reload anyway and your changes will be lost.
Upvotes: 1