Activity Forums Salesforce® Discussions How to insert a user using apex with a contact linked with it in Salesforce?

  • Piyush

    Member
    November 15, 2019 at 6:06 am

    Hi,

    We can crteate a user using apex like this:-

    User u = new user();
    u.LastName = 'Temp';
    u.Email = '[email protected]';
    u.Alias = 'Tc';
    u.Username = '[email protected]';
    u.CommunityNickname = 'test12';
    u.LocaleSidKey = 'en_US';
    u.TimeZoneSidKey = 'GMT';
    u.ProfileID = '00e90000000oyi5';
    u.LanguageLocaleKey = 'en_US';
    u.EmailEncodingKey = 'UTF-8';
    insert u;

    and add contact like this :-

    try {
        Account acct = new Account(Name='Account');
        insert acct;
        // Add a contact to this account.
        Contact con = new Contact(
            FirstName='Jojo',
            LastName='Smoke',
            Phone='7875666677',
            AccountId=acct.id);
        insert con;
    } catch(DmlException e) {
        System.debug('An unexpected error has occurred: ' + e.getMessage());
    }

    I hope this will help you.

  • Yogesh

    Member
    November 15, 2019 at 6:06 am

    Hello,

    you can use this code below:-

    User u = new User();
    u.lastName = ‘Lstname’;
    u.ContactId = contactLookup[0].Id;
    u.Username = ‘username’;
    u.Email = ’email’;
    u.CommunityNickname = ‘nickname’;
    u.Alias = ”;
    u.TimeZoneSidKey = ‘America/Phoenix’; // Required
    u.LocaleSidKey = ‘en_US’; // Required
    u.EmailEncodingKey = ‘ISO-8859-1’; // Required
    u.LanguageLocaleKey = ‘en_US’; // Required
    }

    Hope it helps

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos