How to auto increment a particular field in a doctype?

Based on our private messages, we have developed the code to achieve what was desired here. I’m sharing it for others to be able to use:

{

cur_frm.cscript.custom_customer_name = compute;
function compute(doc, cdt, cdn)
{
    //Find out the first two digits of the code
	temp_code = "";
	switch(doc.customer_name) 
	{
		default:
		temp_code = doc.customer_name.charAt(0);
		temp_code += "C";
	}
	//Get a list of all the exisiting codes with the same first two digits
	frappe.call({ method:"frappe.client.get_list",
		args:{
			doctype: "Customer",
			filters: {"customer_code": ["like", temp_code + "%"]},
			fields: ["name"],
					limit_page_length: 500
		},
		callback: function(r) {
			//Count the number of elements in the list (which will decide what customer code to try)
			if (r.message) {
				temp_code += zeroPad(r.message.length, 5);
							console.log(temp_code );
			}
					else{
				temp_code += "00000";
							console.log(temp_code );
			}
			// You probably want to add a section of code here that checks to see if the new code is an element of the list, 
			// and increment the code if that customer code already exists (this only comes up if a customer is deleted)
			// Otherwise, you could create multiple customers with the same code.
			//Submit the customer code and refresh the field
			doc.customer_code= temp_code;
			refresh_field("customer_code");
		}
	});
}	
function zeroPad(num, places) {
	var zero = places - num.toString().length + 1;
	return Array(+(zero > 0 && zero)).join("0") + num;
}
}
6 Likes