function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Amit Singh.ax1042Amit Singh.ax1042 

How to Create User with the help of Visualforce and Apex..

Hi Friends,

i am getting problem when creating User with the help of visualforce page and Apex class(Apex class is used to view license and profiles))

problem here is about  Profile and  License type... since when we create user through manage users--> user if we select any particular license it shows profile only related to that license...(profile is dependent on license type we are selecting)...

but my page shows all licenses and profiles...

how to filter this??

 

here is my code--

 

</apex:page>

<apex:page standardController="User" extensions="CreateNewStaffAndUserExtension" tabStyle="Admin__c">
 
 
   
<!--    
<apex:sectionHeader title="Welcome" subtitle="{!User.Name}" help="/help/doc/user_ed.jsp?loc=help"></apex:sectionHeader> -->
    <apex:form >
        <apex:pageBlock mode="edit">
        <apex:pageMessages />
            <apex:pageBlockButtons >
                    <apex:commandButton action="{!save}" value=" Save "></apex:commandButton>
                    <apex:commandButton action="{!cancel}" value="Cancel"></apex:commandButton>
                 </apex:pageBlockButtons>
              
              <apex:pageBlockSection title="User Information" columns="2" collapsible="false">  
                
                  <apex:inputField value="{!User.User_Skills__c}" />
                  <apex:inputField value="{!User.IsActive}"/>
                  <apex:inputField value="{!User.FirstName}"/>
                  <apex:inputField value="{!User.Username}"/>
                  <apex:inputField value="{!User.LastName}"/>
                  <apex:inputField value="{!User.Email}"/>
                  <apex:inputField value="{!User.alias}"/>
                  <apex:inputField value="{!User.UserRoleId}"/>
                  
                 
                  </apex:pageBlockSection>
                 <!-- <apex:inputField value="{!User.UserType}"/> -->
            
           
            

              <!--  <apex:pageBlockSectionItem >
                    <apex:outputLabel value="User" for="usr"></apex:outputLabel>
                   
                    <apex:selectList value="{!selectedRoleId}" multiselect="false" size="1" id="selectedRoleId">
                       <apex:selectOptions value="{!userList}" />
                    </apex:selectList>
                    </apex:pageBlockSectionItem>
            
            -->
                    
                    
            <apex:pageBlockSection >
              <!--    <apex:inputField value="{!User.ProfileId}"/> -->
                   <apex:inputField value="{!User.Phone}"/>
                   <apex:inputField value="{!User.Extension}"/>
                   <apex:inputField value="{!User.Fax}"/>
                   <apex:inputField value="{!User.EmployeeNumber}"/>
                   <apex:inputField value="{!User.Title}"/>
                   <apex:inputField value="{!User.CompanyName}"/>
                   <apex:inputField value="{!User.Division}"/>
                   <apex:inputField value="{!User.Department}"/>
                   <apex:inputField value="{!User.CommunityNickName}"/>

                 <!--  <apex:inputField value="{!User.UserType}"/> -->
                   
                   <apex:inputField value="{!User.ReceivesInfoEmails}" />
                   </apex:pageBlocksection>
              
                    <apex:pageBlockSection columns="1" showHeader="false" title="License">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="License" for="lic"></apex:outputLabel>
                    <apex:selectList id="mgr" value="{!User.UserType}" size="1" title="Manager">
                        <apex:selectOptions value="{!license}"></apex:selectOptions>
                    </apex:selectList>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Profile" for="pro"></apex:outputLabel>
                   
                    <apex:selectList value="{!User.ProfileId}" multiselect="false" size="1" id="selectedProfileId">
                       <apex:selectOptions value="{!profile}" />
                    </apex:selectList>
                    </apex:pageBlockSectionItem>
            </apex:pageBlockSection> 
            
              
              
               <apex:pageBlockSection title="Other Information" columns="1" collapsible="false">
                   <apex:inputField value="{!User.EmailEncodingKey}"/>
                   <apex:inputField value="{!User.TimeZoneSidKey}"/> 
                   <apex:inputField value="{!User.LocaleSidKey}"/>
                   <apex:inputField value="{!User.LanguageLocaleKey}"/>
               </apex:pageBlockSection>
               
            <!--   <apex:pageBlockSection columns="1" showHeader="false" title="License">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="License" for="lic"></apex:outputLabel>
                    <apex:selectList id="mgr" value="{!User.UserType}" size="1" title="Manager">
                        <apex:selectOptions value="{!license}"></apex:selectOptions>
                    </apex:selectList>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
            
            -->
            
              </apex:pageBlock>
              </apex:form>
   
 


    
Apex Class is-:
}

public class CreateNewStaffAndUserExtension {


   
    public Id accountId{get;set;}
    public String accountName{get;set;}

      public List<Account> accs{get;set;}

    private final User user;
    public CreateNewStaffAndUserExtension(ApexPages.StandardController controller)
    {
    
 
      this.user= (User)controller.getrecord();

    }
    
 
    public List<selectOption> getLicense()
    {
        List<selectOption> options = new List<selectOption>(); //new list for holding all of the picklist options
        options.add(new selectOption('', '- None -')); //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
          for (UserLicense users :[SELECT Id,Name FROM UserLicense])  
          {    
                options.add(new selectOption(users.Id, users.Name)); //for all records found - add them to the picklist options
          }
        return options; //return the picklist options
    }
    
    public List<selectOption> getProfile() {
        List<selectOption> options1 = new List<selectOption>(); //new list for holding all of the picklist options
        options1.add(new selectOption('', '- None -')); //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
     //   for (User users : [SELECT Id,UserType FROM User]) { //query for User records with System Admin profile
     for (Profile users1 :[SELECT Id,Name FROM Profile])  {    
                options1.add(new selectOption(users1.Id, users1.Name)); //for all records found - add them to the picklist options
        
        
        
        
        } 
        
        
        return options1; //return the picklist options 
   
   
    } 
  
    
 }

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

You'll need to rerender the profile picklist once the user has made their selection:

 

 <apex:pageBlockSectionItem >
      <apex:outputLabel value="License" for="lic"></apex:outputLabel>
      <apex:selectList id="mgr" value="{!User.UserType}" size="1" title="Manager">
         <apex:selectOptions value="{!license}"></apex:selectOptions>
         <apex:actionSupport event="onchange" rerender="selectedProfileId"/>
   </apex:selectList>
</apex:pageBlockSectionItem>

 

and in the controller, generate the profiles based on the selected license:

 

  public List<selectOption> getProfile() {
        List<selectOption> options1 = new List<selectOption>(); //new list for holding all of the picklist options
        options1.add(new selectOption('', '- None -')); //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
     //   for (User users : [SELECT Id,UserType FROM User]) { //query for User records with System Admin profile
     for (Profile users1 :[SELECT Id,Name FROM Profile where UserLicenseId=:user.UserType])  {    
                options1.add(new selectOption(users1.Id, users1.Name)); //for all records found - add them to the picklist options
        
        
        
        
        } 

 

All Answers

Amit Singh.ax1042Amit Singh.ax1042

and one more thing i want to ask...

if we are creating user through visual force and apex...

can we give license type and Profile default (means i want to create user with visualforce who is having chatter free license and chatter free Profile)...

if i dont want option for license type and profile in my vf page... is it possible???

(because both field are mandatory ...can we give default value?) 

bob_buzzardbob_buzzard

A profile has a lookup to a UserLicense sobject, which in turn contains the name of the license.  Thus once you have selected a license for the user, you can restrict the profiles retrieved to those where the UserLicenseId matches that of the selected license.

Amit Singh.ax1042Amit Singh.ax1042

could you tell me what modifications are required in my visualforce page and apex class??

 

 

bob_buzzardbob_buzzard

You'll need to rerender the profile picklist once the user has made their selection:

 

 <apex:pageBlockSectionItem >
      <apex:outputLabel value="License" for="lic"></apex:outputLabel>
      <apex:selectList id="mgr" value="{!User.UserType}" size="1" title="Manager">
         <apex:selectOptions value="{!license}"></apex:selectOptions>
         <apex:actionSupport event="onchange" rerender="selectedProfileId"/>
   </apex:selectList>
</apex:pageBlockSectionItem>

 

and in the controller, generate the profiles based on the selected license:

 

  public List<selectOption> getProfile() {
        List<selectOption> options1 = new List<selectOption>(); //new list for holding all of the picklist options
        options1.add(new selectOption('', '- None -')); //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
     //   for (User users : [SELECT Id,UserType FROM User]) { //query for User records with System Admin profile
     for (Profile users1 :[SELECT Id,Name FROM Profile where UserLicenseId=:user.UserType])  {    
                options1.add(new selectOption(users1.Id, users1.Name)); //for all records found - add them to the picklist options
        
        
        
        
        } 

 

This was selected as the best answer
Amit Singh.ax1042Amit Singh.ax1042

Thank you very much Bob :)

Amit Singh.ax1042Amit Singh.ax1042

Bob,

is it possible to take license and profile value default...

i mean ... when i create user with the help of visualforce... can i take these two fields default(hiding it on Interface)...

say license-chatter free and profile chatter free

is it possible??

if yes then how?

bob_buzzardbob_buzzard

Yeah, that's possible.

 

Just add something like the following to your constructor:

 

  public CreateNewStaffAndUserExtension(ApexPages.StandardController controller)
    {
    
 
      this.user= (User)controller.getrecord();
      user.UserType=[select id from UserLicence where name = 'Chatter Free'].id; user.ProfileId=[select id from Profile where name='Chatter Free User'].id;

    }

There's some bad practice above - assuming the query will always return a single object, harcoded names, but hopefully you get the idea.

Amit Singh.ax1042Amit Singh.ax1042

Bob,I have tried this,but i am getting error

 

Error: Compile Error: sObject type 'UserLicence' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names. at line 14 column 21

 

How to resolve this??

is I need to make modification in vf page (now i am not taking license and profile in my vf page- it is hidden).

bob_buzzardbob_buzzard

Typo on my part - I used the English spelling!

 

Change to:

 

user.UserType=[select id from UserLicense where name = 'Chatter Free'].id; user.ProfileId=[select id from Profile where name='Chatter Free User'].id;

 

Amit Singh.ax1042Amit Singh.ax1042

bob it is working,

but now i am facing similar kind of problem...

i want to give default value for EncodingKey,TimeZoneSidKey,LocaleSidKey,LanguageLocaleKey (hidden on User Interface).

 

for this i have used following code in my controller(here i have shown only EmailEncodingKey)-:

 

public CreateNewUserExtension(ApexPages.StandardController controller)
    {
   
                        this.user= (User)controller.getrecord();
                        user.ProfileId=[select id from Profile where name='Chatter Free User'].id;
/* line16 */      user.EmailEncodingKey=[select id from User where EmailEncodingKey = 'General US @ Western Europe (ISO-8859-1,ISO-LATIN-1)'].Id;
     
    }

 

getting Error like this-:

 

System.QueryException: List has no rows for assignment to SObject 
Class.metasysmanaged.CreateNewUserExtension.: line 16, column 29 External entry point

 

 

How to solve this issue??