Autoname username field

Hi everyone,

I want to autoname the username field in user doctype, but I want to pick the name initials and a count number, for example:

Fullname: Jhon Dallas Speck
Username: JDS1

Is there a way to acomplish this?

below post is the soultion

Hi @garciagonpablo,

frappe.ui.form.on('User', {
    validate: function(frm) {
        setUniqueUserName(frm);
    }
});

function setUniqueUserName(frm) {
    var username = getUserNameFromFullName(frm.doc.full_name);
    var count = 1;

    while (true) {
        var existingUser = frappe.get_doc('User', { 'username': username });
        if (!existingUser) {
            frm.set_value('username', username);
            break;
        }

        username = getUserNameFromFullName(frm.doc.full_name) + count;
        count++;
    }
}

function getUserNameFromFullName(fullName) {
    var nameParts = fullName.split(' ');
    var firstName = nameParts[0];
    var lastName = nameParts.length > 1 ? nameParts[nameParts.length - 1] : '';
    var initials = firstName[0].toUpperCase() + (lastName ? lastName[0].toUpperCase() : '');
    return initials;
}

Output:

User 1: Ravi Kumar -> RK
User 2: Ravi Kumar -> RK1
User 3: Ravi Kumar -> RK2

It is a makeshifter script so please try it. maybe it help you.

Thank You!

1 Like