One of the most common requirements in Dynamic CRM is to
view the age of the customer/contact or individuals. It seems to be pretty
straight forward but it is a bit challenging.
First, I tried calculating Age from Business User favorites
which is – Business Rules in Dynamic
CRM.
Business Rule was giving me a hard time and then I
moved myself to the Developers favorites – JavaScript.
Below JavaScript code is pretty straight forward and
we just need to register event on change of a Birthdate of any other date
field. I created a new firld new_age
of type Whole Number.
function
onChange_birthdate()
{
    var
birthday = Xrm.Page.getAttribute("birthdate").getValue();
    if
(birthday != null)
    {
        var
age = calculate_age(birthday.getMonth(), birthday.getDate(),                                  birthday.getFullYear());
        Xrm.Page.getAttribute("new_age").setValue(age);
        Xrm.Page.getAttribute("new_age").setSubmitMode('always');
    }
}
function
calculate_age(birth_month, birth_day, birth_year)
{
    today_date = new
Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;
    if
(today_month < (birth_month))
    {
        age--;
    }
    if
(((birth_month) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return
age;
}
Hope this is help!
Thanks.
Vipin Jaiswal



 
 
1 comment:
this could land us in a problem after a year,
the age field will be 1 year less than actual value.
Again you need to write C# batchjob to update the records.
We cant wait for users to open each record and update the value using js
Post a Comment