Is there any API that allows me to check if a Username is in use?

We are creating our own ISV trial provisioning page and using the SignupRequest API to create trials. I can’t seem to figure out a way to check for the availability of a username synchronously. Unfortunately, the only way to figure out if a username is taken is to signup and then the user gets a pretty generic failure email with a link back to the wrong trial page (the standard Salesforce trial signup page). I would rather check for the existence of a username while the user is filling out the form if possible. Is there any API that enables this?

Answer

No need for an API. Just use synchronous Apex code instead.

Simply create and insert a User in a try and check for the right exception in the catch and always rollback the insert in the finally.

This class should do the job.

public class UserService {
    public static Boolean existsName(String fullUserName) {
        Boolean result = false;

        User user = new User();  
        user.FirstName = 'any';
        user.LastName = 'any';
        user.Alias = 'any';
        user.EMail = 'any@email.com';
        user.Username = fullUserName;
        user.CommunityNickname = fullUserName;
        user.LocaleSidKey = 'en_US';
        user.LanguageLocaleKey = 'en_US';
        user.EmailEncodingKey = 'UTF-8';
        user.TimeZoneSidKey = 'America/Los_Angeles';
        user.ProfileId = [SELECT Id, Name FROM Profile WHERE Name='Standard User' limit 1].Id;

        Savepoint sp = Database.setSavepoint();

        try {
            insert user;
        }
        catch(DmlException ex) {
            if(ex.getDmlStatusCode(0) == StatusCode.DUPLICATE_USERNAME.name()) {
                result = true; 
            }
        }
        finally {
            Database.rollback(sp);
        }

        return result;
    }
}

Attribution
Source : Link , Question Author : greenstork , Answer Author : Robert Sösemann

Leave a Comment