How do I calculate a field value based on the pervious field value inside a custom doctype?

I want to create a custom doctype where I want to do a calculation based on the previous field. For example there are two fields, first is number of working days which is a data type and second field is one day salary which is fetched from another doctype. So, I want to show the calculated salary in the second field based on number of working days which I’ve typed in the first field. Is there anything like trigger or onClick in the ERPNext ?

In this image I’ve selected an employee and based on the employee I’m getting the Basic which is 500 and in the Working Days I’ve entered 25. So, I want 25*500 = 12,500 in the Basic. So, I can I achieve here in the ERPNext ?

Hi:

Add other field called “Total” to the doctype.
Create a client script for “New Salary Form” doctype.
Let’s say that your field Working Days → working_days and Basic → basic

Script would be like this:

frappe.ui.form.on('New Salary Form', {
	days_working(frm) {
		frm.set_value("total", frm.doc.days_working * frm.doc.basic)
	}
})

Remind enable it.

Docs avaliable here:
https://frappeframework.com/docs/user/en/desk/scripting/client-script

See this amazing video from @buildwithhussain … and suscribe to the channel. You will learn a lot of things.

Hope this helps.

1 Like

@avc Thank you for this solution. Now, I can calculate an employee’s salary based on the working days. I’m using smore more condition in the script and I’m getting the calculated amount in decimal points like 1200.57656465656. How can I remove the decimal points.

frappe.ui.form.on(‘New Salary form’, {
working_days(frm) {
frm.set_value(“basic”, frm.doc.working_days * ((frm.doc.basic * 30) / frm.doc.calender_days))
}
})

Hi @Rahul_Singh:

Try this …

frappe.ui.form.on(‘New Salary form’, {
working_days(frm) {
frm.set_value(“basic”, Math.round(frm.doc.working_days * ((frm.doc.basic * 30) / frm.doc.calender_days)))
}
})

Hope this helps.

1 Like

@avc Yes, it is working. Thanks again.

1 Like

@avc Hi,

Can we assign multiple values to one variable here ? I want to show the number of days based on a month. For this I’ve created three fields calendar_days31, calendar_days28, calendar_days30. But I’m using a condition like If Month = January then I’m showing 31 in days field and similarly for 28 and 30 days. So, can you please tell me how can I assign multiple values to one variable.

frappe.ui.form.on('Custom Salary Slip', {
	working_days(frm) {
	    calender_days = frm.doc.calendar_days31;
	    calender_days = frm.doc.calendar_days28;
	    calender_days = frm.doc.calendar_days30;
		frm.set_value("basic", Math.round(frm.doc.working_days * ((frm.doc.basic * 30) / calender_days)))
	}
})