Name: PortalUserCreation Usage: This trigger is used to send mail to Portal User which are created from Self Registration Object

trigger PortalUserCreation on Self_Register_User_Request__c (before update) {

    String DUMMY_ACCOUNT  = 'Dummy Account' ;
    List<Contact> conListToInsert = new List<Contact>();

    Map<Id, String> emailMap = new Map<Id, String>();
    Map<Id, Self_Register_User_Request__c> dummyMap = new Map<Id, Self_Register_User_Request__c>();

    for(Self_Register_User_Request__c sr :trigger.new) { 
        System.debug('here is FN: '+sr.FirstName__c);
        System.debug('here is FN: '+sr.LastName__c);
        System.debug('here is FN: '+sr.Email__c);
        System.debug('here is FN: '+sr.AccountName__c);
        if(sr.FirstName__c == null || sr.LastName__c == null || sr.Email__c == null)  
            continue;      
           if(sr.Is_it_Approved__c  = TRUE){
            if(sr.AccountName__c != null ){
                Contact conRecord = new Contact(
                    FirstName = sr.FirstName__c,
                    LastName = sr.LastName__c,
                    Email = sr.Email__c,
                    AccountId = sr.AccountName__c
                );              
                System.debug('adding contact from line 36');
                conListToInsert.add(conRecord); 
            }

            if(sr.Email__c != null){
                emailMap.put(sr.Id, sr.Email__c);           
            }

            dummyMap.put(sr.Id, sr);                    
        }
    }
    //create Portal User
    if(conListToInsert != null && conListToInsert.size() > 0) {
        insert conListToInsert;
        List<Profile> pList = [select id from Profile where Name = 'Partner Community Login User - Custom'];
        if(!pList.isEmpty()){
            Profile p = pList[0];
            List<User> userListToInsert = new List<User>();
            for(Contact con :conListToInsert) {             
                String alias1 = '';
                if(con.FirstName.length() >= 0)
                    alias1 = con.FirstName.substring(0,1);

                String alias2 = '';
                if(con.LastName.length() >= 4){
                    alias2 = con.LastName.substring(0, 4);        
                }else{
                    alias2 = con.LastName;
                }
                String alias = alias1 + alias2;
                User u = new User(
                    Alias = alias, 
                    Email = con.Email,
                    EmailEncodingKey = 'UTF-8', 
                    FirstName = con.FirstName,
                    LastName = con.LastName, 
                    LanguageLocaleKey = 'en_US', 
                    LocalesIdKey = 'en_US', 
                    ProfileId = p.Id, 
                    ContactId = con.id,
                    TimeZonesIdKey = 'America/Los_Angeles', 
                    UserName = con.Email
                );
                Database.DMLOptions dmo = new Database.DMLOptions();
                dmo.EmailHeader.triggerUserEmail = true;
                u.setOptions(dmo);
                userListToInsert.add(u);
            }

            Database.SaveResult[] results = database.insert(userListToInsert, false);
            for(Database.SaveResult sr :results){
               if(!sr.isSuccess()){
                  Database.Error err = sr.getErrors()[0];
                  throw new CustomException(err.getMessage());
                                    }
            }                       
        }        
    }  



    //define your custom exception
    public class CustomException extends Exception{}

Test CLass:

@isTest
private class PortalUserCreationTest {

    static TestMethod void myUnitTest()
    {
        Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);

         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'XYZanjkaeanflamdfldfaf123@test.com',
            Alias = 'batman',
            Email='testtermscon123dit123ions1234423@mycomany.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;


        System.runas(u) {

        Account acc = new Account();
            acc.Name ='Test1';
            acc.Account_Type__c = 'Reseller';
            acc.New_Account_Source__c = 'Advertisement';

        insert acc;


        Test.startTest();
            Self_Register_User_Request__c  selfregister =  new Self_Register_User_Request__c ();
                                                                       selfregister.FirstName__c='Sree';
                                                                       selfregister.LastName__c='Chandra';
                                                                       selfregister.Email__c='Test@gmail.com';
                                                                       selfregister.Company_web_site__c='WWW.DST.com';
                                                                       selfregister.Company__c='DST';
                                                                       selfregister.AccountName__c= acc.id;
                                                                        selfregister.Is_it_Approved__c  =False ; 
                                                                       insert selfregister ;


            selfregister.AccountName__c= acc.id;

            selfregister.Is_it_Approved__c  =True ; 

            update selfregister;                                                      



        Test.stopTest();
        }
    }
}

i am getting error like:

Error Message System.DmlException: Update failed. First exception on row 0 with id a591g00000087sgAAA; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, PortalUserCreation: execution of BeforeUpdate

caused by: PortalUserCreation.CustomException: Duplicate Username.
The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address).

Trigger.PortalUserCreation: line 85, column 1: [] Stack Trace Class.PortalUserCreationTest.myUnitTest: line 64, column 1

New contributor
swaroopa is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • I've removed the commented portions of your code to reveal what remains. It appears to me that your unit test is not only trying to create a partner portal user, but also trying to update the account at the same time. I think you want to insert and update the account before creating the user. – crmprogdev Oct 11 at 14:40
  • i dont need any account update i only need to create a user. I have inserted an account details in test class for the self registration object details. from Using self registration fields it creates a contact and portal user. Please edit my test class code and send me pls – swaroopa Oct 11 at 16:02

Your Answer

swaroopa is a new contributor. Be nice, and check out our Code of Conduct.
 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.