2014-10-05 135 views
2

我需要編寫一個全球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 ..可以幫助你嗎?

回答

3

您用於計算年齡的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