ERPNext Foundation ERPNext Cloud User Manual Blog Discuss Frappé* Donate

Calculate Employee age from Date of Birth

customization
custom_field

#1

I have created a custom field called age on the employee form.

I want to display the age of an employee in the age field after the user inputs the date of birth and sets focus to another field. This is my script:

frappe.ui.form.on("Employee", "age", function(frm) {
  var dob = new Date(frm.doc.date_of_birth);
  var now = new Date();
  var age_now = now.getFullYear() - dob.getFullYear();

  cur_frm.set_value("age", age_now);
  cur_frm.refresh();
});

However, nothing happens to the age field.

Please assist.


#2

This a sample test to calculate age I used in my work
JS code:

frappe.ui.form.on('DoctypeName', {
	refresh: function (frm) {
		
	},
	onload: function (frm) {
		if(frm.doc.dob){
			$(frm.fields_dict['age_html'].wrapper).html("AGE : " + get_age(frm.doc.dob));
		}
	}
});

frappe.ui.form.on("DoctypeName", "dob", function(frm) {
	if(frm.doc.dob){
		var today = new Date();
		var birthDate = new Date(frm.doc.dob);
		var age_str = get_age(frm.doc.dob);
		$(frm.fields_dict['age_html'].wrapper).html("AGE : " + age_str);
	}
});

var get_age = function (birth) {
	var ageMS = Date.parse(Date()) - Date.parse(birth);
	var age = new Date();
	age.setTime(ageMS);
	var years = age.getFullYear() - 1970;
	return years + " Year(s) " + age.getMonth() + " Month(s) " + age.getDate() + " Day(s)";
};

Python code:

def get_age(self):
		age_str = ""
		if self.dob:
			born = getdate(self.dob)
			age = dateutil.relativedelta.relativedelta(getdate(), born)
			age_str = str(age.years) + " year(s) " + str(age.months) + " month(s) " + str(age.days) + " day(s)"
		return age_str
  • dob is the name of the Date of Birth field
  • age_html is the name of the Age field with HTML fieldtype

#3

@OmarJaber

Thank you very much. After tweaking it a little, I got it to work. A great script to start from.


#4

Hi @kevingee, do you mind to share how you do it?