Calculate data and insert it into doctype

Hello Community,

I’ve made a goals table that contains goals and whether it is completed or not. and I want to calculate the total percentage of goals that have been completed and fill that field with server-side calculation after the user save that form. Visual representation attached below:

For instance, the above form field that is “Percentage (%)” should be filled with 60.0

Thanks

There are a few different ways to do this, and the documentation covers most of them.

https://frappeframework.com/docs/v13/user/en/desk/scripting/server-script

I’m having an issue with passing the argument in JS file, can you help me how to pass the calculated argument in python file

JS FILE

frappe.ui.form.on('Goal Doc', {

	after_save: function(frm){

		frappe.call({
			method: "erpnext.hr.doctype.goal_doc.goal_doc.get_check_count",
			args: {
				perc: perc
			},
			callback: function(r){
				console.log(r)
				frappe.model.set_value(frm, "percentage_", r.message);
			}
		});
	}
});

PY FILE

class GoalDoc(Document):

	def validate(self):
		count = 0
		total = 0
			
		for i in self.goals:

			if True:
				total = total + 1

			if i.completed:
				count = count + 1
		
		perc = (count/total) * 100

		get_check_count(perc)

@frappe.whitelist()
def get_check_count(perc):
	return perc

This code doesn’t really make sense. Your method get_check_count doesn’t do anything except return the value sent to it. I don’t really understand why you’re calling it from both your validation method and your client script.

Also, you definitely don’t want to be calling this hook after save (nor in validation). You want to do it before save. Something like this:

class GoalDoc(document):

    def before_save(self):
        count = 0
        for i in self.goals:
            if i.completed:
                count = count + 1
        self.perc = count / len(self.goals) * 100

This is untested code, so it may contain bugs.