Tuesday 12 March 2013


Create customer portal user in Apex

Creating (Converting contact into user) customer portal user is basic requirement for writing test cases (may be a requirement) in Salesforce as we know customer portal users contains different profile like the customer portal user's custom profile so first of all assign customer portal profile to user and then create customer portal user, we can use customer portal user in other requirement as well so here we have an example (Apex code script) that will convert contact into customer portal user.

Apex Script
/*
    @Author: Mohammad Usman
    @Description: Create customer portal user
*/
//Retrive a contact from database 
Contact objectContact = [SELECT FirstName,LastName,Email 
                         FROM Contact Where Email <> null limit 1];
//To get converted contact into user
User objContactUser = getConvertedUserFormContact(objectContact);
System.debug('Contact User Deatils:'+objContactUser);
/*  
    @Param: Contact Record
    @description: Pass contact as an argument that 
    contact will be convert into customer portal user.
*/
public User getConvertedUserFormContact(Contact objContact){    
    try{
        if(objContact != null){
            //Select Exist Customer portel User's profile
            Profile pf = [SELECT Id FROM profile 
                          WHERE name='Custom Portal User Profile' limit 1];   
            //Create user 
            User mockUser = new User(contactId=objectContact.Id, 
                            username=objectContact.Email, 
                            firstname=objectContact.FirstName,
                            lastname=objectContact.LastName, 
                            email=objectContact.Email,
                            communityNickname = objectContact.LastName + '_'+Math.random(),
                            alias = string.valueof(objectContact.FirstName.substring(0,1) + 
                                    objectContact.LastName.substring(0,1) + Math.random() ), 
                            profileid = pf.Id, emailencodingkey='UTF-8',
                            languagelocalekey='en_US', 
                            localesidkey='en_US', 
                            timezonesidkey='America/Los_Angeles');                  
            insert mockUser;
        return mockUser;
    }catch(Exception ex){
        throw ex;
    }
    return null;
}

1 comment:

  1. Thank for post.
    I need some more functionality,
    When portal user creates password and username should be send to contacts email id.
    But here where we r getting uname and password?
    please replay to this query?

    ReplyDelete

    Links