通过出生日期字段在crm 2013年计算年龄

通过出生日期字段在crm 2013年计算年龄

问题描述:

我需要编写一个全球JavaScript代码,根据生日字段计算年龄并从不同的JavaScript文件调用函数到特定的实体。 由于某种原因我收到我的实体javascript文件到窗体后出现错误消息“CalculateAge is undefined”。通过出生日期字段在crm 2013年计算年龄

这是我在全局文件中写:

CalculateAge: function (birthd) 
{ 
    if (birthd == null) { 
     return;} 
    var today = new Date().getFullYear(); 
    year1 = birthd.getFullYear(); 
    return (today-year1); 
} 

这是我写在我的实体文件我加载到窗体:

function onLoad() { 

     var birthDate = Xrm.Page.getAttribute("el_birth_date").getValue(); 
     Xrm.Page.getAttribute("el_age").setValue(CalculateAge(birthDate)); 

    } 

我新的Javascript ..可以帮助你吗?

您用于计算年龄的JavaScript代码不正确,它不考虑月份和日期。 正确的版本是这样一个:

function CalculateAge(birthday, ondate) { 
    // if ondate is not specified consider today's date 
    if (ondate == null) { ondate = new Date(); } 
    // if the supplied date is before the birthday returns 0 
    if (ondate < birthday) { return 0; } 
    var age = ondate.getFullYear() - birthday.getFullYear(); 
    if (birthday.getMonth() > ondate.getMonth() || (birthday.getMonth() == ondate.getMonth() && birthday.getDate() > ondate.getDate())) { age--; } 
    return age; 
} 

,并可以用作:

var birthday = Xrm.Page.getAttribute("new_birthday").getValue(); 
var age = CalculateAge(birthday); 
alert(age); 
// age on 1st January 2000, JavaScript Date() object contains months starting from 0 
var testdate = new Date(2000, 0, 1, 0, 0, 0); 
var testage = CalculateAge(birthday,testdate); 
alert(testage); 

如果你没有定义CalculateAge,也许你不包括含表单内的功能webresource 。如果您有两个JS Web资源(一个包含函数,另一个包含onLoad事件)都需要包含在表单中。

如果您在CRM版本中存在异步JavaScript加载问题,最好在与onLoad事件相同的文件中包含CalculateAge函数,但如果您愿意将它们分开检查此博客文章:Asynchronous loading of JavaScript Web Resources after U12/POLARIS

JavaScript函数来自我的博客文章:Calculate age in Microsoft Dynamics CRM 2011

+0

谢谢!我做了它,现在它的工作..但不幸的是,我现在有另一个问题..我需要定义年龄字段不保存插入数据库中的数据,所以我写在实体JS文件中:Xrm.Page.getAttribute(“ el_age “)setSubmitMode(” 从不“); ----问题是当我在第一次保存表单时,几秒钟后,age字段中的值被删除,当我再次保存它时,OK ......你能帮忙吗? - – userS 2014-10-05 08:51:26