Home Blog How to Calculate the Field Based on the other Field via JS: ERPNext
How to Calculate the Field Based on the other Field via JS: ERPNext

How to Calculate the Field Based on the other Field via JS: ERPNext


Scenario: Creating a custom field named "age" in the "Employee" doctype and utilizing the default HRMS field "date_of_birth" to perform the calculation.

  


Step 1: Create a JavaScript File


Begin by creating a JavaScript file named "employee.js" in the public directory of your app. The path to this file should be "/my_app/public/js/employee.js."



Step 2: Write the JavaScript Code


Inside "employee.js," add the following JavaScript code:


frappe.ui.form.on("Employee", {
    date_of_birth(frm) {
        var birthdate = frm.doc.date_of_birth;

        // Calculate age based on date of birth
        var dobDate = new Date(birthdate);
        var today = new Date();
        var age = today.getFullYear() - dobDate.getFullYear();
        if (today.getMonth() < dobDate.getMonth() || (today.getMonth() === dobDate.getMonth() && today.getDate() < dobDate.getDate())) {
            age--;
        }

        frm.set_value("age", age);
    }
})

Ensure that the function name "date_of_birth" matches the field name in the "Employee" doctype.



Step 3: Integrate JavaScript File in Hooks


In order for ERPNext to recognize and use the JavaScript file, you need to define it in the "hooks.py" file. Add the following line to the "hooks.py" file:



Step 4: Observe the Result


Once you've completed these steps, the "age" field in the "Employee" doctype will automatically update when you change the "date_of_birth" field. The JavaScript code calculates the age based on the provided date of birth and sets the "age" field accordingly.


Note: Using this method, the "age" field will not be set as read-only, allowing you to manually change the value if needed.


 Subscribe our Newsletter for erpnext tips, technical insights, and more!



By following these steps, you can easily calculate an employee's age in ERPNext based on their date of birth, improving the accuracy and efficiency of your HR management processes. 



Get In Touch with Us

Leave a Comment

Your email address will not be published.

Submit
Your comment is under review by our moderation team.