Author Archives: Biswajeet

About Biswajeet

Biswajeet is my Name, Success is my Aim and Challenge is my Game. Risk & Riding is my Passion and Hard Work is my Occupation. Love is my Friend, Perfection is my Habit and Smartness is my Style. Smiling is my Hobby, Politeness is my Policy and Confidence is my Power.

Reset User Password in Salesforce Using Apex

In Salesforce there are two methods to set password and to reset password for a user.

resetPassword(Id userId, Boolean sendUserEmail): This method resets the password for the specified user. When the user logs in with the new password, they are prompted to enter a new password, and to select a security question and answer if they haven’t already. If you specify true for sendUserEmail, the user is sent an email notifying them that their password was reset. A link to sign onto Salesforce using the new password is included in the email.

setPassword(Id userId, String password): Sets the password for the specified user. When the user logs in with this password, they are not prompted to create a new password.

Sample Code:

List<User> users = new List<User>();
String username = 'test@test.com';
users = Database.Query('SELECT Id, Name FROM User WHERE UserName  =: username');

for(User u : users){
    //For reset User password
    System.resetPassword(u.Id, true);
    
    //For set User password
    //System.setPassword(u.Id, 'Test@1234');
}

Using OFFSET in SOQL

When expecting many records in a query’s results, we can display the results in multiple pages by using the OFFSET clause in a SOQL query. We can use OFFSET keyword in SOQL to specify the starting row from the result returned by the query. For example if there are 50 records then, if we specify offset as 20 in the query then it would return record 21 to 50, it will skip first 20 records.

In the following example the query will return rows 11 through 110, and will skip first 10 rows.

SELECT Name, AccountNumber, Type
FROM Account
WHERE Type = 'Customer - Direct'
ORDER BY Name
LIMIT 100
OFFSET 10

Considerations to Use OFFSET:

  • The maximum offset is 2,000 rows. Requesting an offset greater than 2,000 results in a NUMBER_OUTSIDE_VALID_RANGE error.
  • A sub-query can use OFFSET only if the parent query has a LIMIT 1 clause.
  • OFFSET cannot be used as a sub-query in the WHERE clause, even if the parent query uses LIMIT 1.
  • Salesforce recommend using an ORDER BY clause when you use OFFSET to ensure that the result set ordering is consistent. The row order of a result set that does not have an ORDER BY clause has a stable ordering, however the ordering key is subject to change and should not be relied on.
  • Also Salesforce recommend using a LIMIT clause with OFFSET if you need to retrieve subsequent subsets of the same result set.
  • OFFSET clause can be used to implement pagination in visualforce page tables.
  • OFFSET is applied to the result set returned at the time of the query. No server-side cursor is created to cache the full result set for future OFFSET queries. The page results may change if the underlying data is modified during multiple queries using OFFSET into the same result set.
  • When using OFFSET, only the first batch of records are returned for a given query. If you want to retrieve the next batch, you’ll need to re-execute the query with a higher offset value.
  • The OFFSET clause is allowed in SOQL used in SOAP API, REST API, and Apex. It’s not allowed in SOQL used within Bulk API or Streaming API.

Transient Variable in Salesforce

Transient keyword to declare instance variable that can not be saved and should not transmitted as part of view state for visual force page. This helps us reducing the view state of visualforce page. As we all know that, there is a limit of 135KB of viewstate and many times this Transient keyword helps us to reduce the view state.

In below example I have created two Datetime variable, one is with transient keyword and another one is without transient keyword and populating value with both variables. I used Refresh button to refresh the Visualforce page, however only Datetime dt2Controller:

public class SampleController {
    DateTime dt1;
    transient DateTime dt2;
    
    public String getDT1() {
        if (dt1 == null) dt1 = System.Now();
        return '' + dt1;
    }
    
    public String getDT2() {
        if (dt2 == null) dt2 = System.Now();
        return '' + dt2;
    }
}

Visualforce Page:

<apex:page controller="SampleController">
    Datetime 1: {!dt1} <br/>
    Datetime 2: {!dt2} <br/>
    <apex:form >
        <apex:commandLink value="Refresh"/>
    </apex:form>
</apex:page>

Display Multiselect Picklist as Checkboxes in Visualforce Page

In below example I’ve created a custom multiselect picklist “Interests” on “Student” custom object. I’m displaying multiselect picklist to checkboxes in visualforce page.

Multiselect Picklist Field:

Controller:

public class SampleControllerExtn {
    public Student__c student {get;set;}
    
    public SampleControllerExtn(ApexPages.StandardController stdCtrl) {
        student = (Student__c)stdCtrl.getRecord();
    }
    
    public void saveStudent(){
        Upsert student;
    }
    
    //get the multi-select pick list values
    public List<SelectOption> getMSPicklist {
        get {
            List<SelectOption> options = new List<SelectOption>();
            for( Schema.PicklistEntry obj : Student__c.Interests__c.getDescribe().getPicklistValues()) {
                options.add(new SelectOption(obj.getValue(), obj.getLabel()));
            } 
            return options;
        }  
        set;
    }
    
    //get and set the multi-select pick list as checkboxes
    public String[] MSItems { 
        get {
            List<String> selected = new List<String>();
            List<SelectOption> options = this.getMSPicklist;
            for(SelectOption obj : options) {
                if (this.student.Interests__c !=null && this.student.Interests__c.contains(obj.getValue()))
                    selected.add(obj.getValue());
            }
            return selected;
        }public set {
            String selectedCheckBox = '';
            for(String s : value) {
                if (selectedCheckBox == '') 
                    selectedCheckBox += s;
                else selectedCheckBox += ';' + s;
            }
            student.Interests__c = selectedCheckBox;
        }
    } 
}

Visualforce Page:

<apex:page standardController="Student__c" extensions="SampleControllerExtn" tabStyle="Student__c">
    <apex:form>
        <apex:pageBlock>
            <apex:pageblockSection title="Student Details" columns="1" collapsible="false">
                <apex:inputfield value="{!student.name}"/>
                <apex:selectcheckboxes layout="pageDirection"  value="{!MSItems}" label="Interests">                   
                    <apex:selectoptions value="{!getMSPicklist}"/>      
                </apex:selectcheckboxes>
            </apex:pageblockSection>
            <apex:pageblockButtons>
                <apex:commandButton value="Save" action="{!saveStudent}"/>                
            </apex:pageblockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:

Custom Multiselect Picklist Field in Visualforce Page

Controller:

public class SampleController {
    
    Set<String> picklistValues = new Set<String> {'New York','California','Texas','Los Angeles','Chicago','San Francisco', 'Washington'};
    Public List<String> leftSelected {get;set;}
    Public List<String> rightSelected {get;set;}
    Set<String> leftValues = new Set<String>();
    Set<String> rightValues = new Set<String>();
    
    public SampleController(){
        leftSelected = new List<String>();
        rightSelected = new List<String>();
        leftValues.addAll(picklistValues);
    }
    
    public PageReference getSelect(){
        rightSelected.clear();
        for(String s : leftSelected){
            leftValues.remove(s);
            rightValues.add(s);
        }
        return null;
    }
    
    public PageReference getDeselect(){    
        leftSelected.clear();
        for(String s : rightSelected){
            rightValues.remove(s);
            leftValues.add(s);
        }
        return null;
    }
    
    public List<SelectOption> getDeselectedValues(){
        List<SelectOption> options = new List<SelectOption>();
        List<String> objList = new List<String>();
        objList.addAll(leftValues);
        objList.sort();
        for(String s : objList){
            options.add(new SelectOption(s,s));
        }
        return options;
    }
    
    public List<SelectOption> getSelectedValues(){
        
        List<SelectOption> options = new List<SelectOption>();
        List<String> objList = new List<String>();
        objList.addAll(rightvalues);
        objList.sort();
        for(String s : objList){
            options.add(new SelectOption(s,s));
        }
        return options;
    }
}

Visualforce Page:

<apex:page controller="SampleController">
    <apex:form>
        <apex:panelGrid columns="3" id="abcd">
            <apex:selectList id="sel1" value="{!leftSelected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!DeselectedValues}" />
            </apex:selectList>
            
            <apex:panelGroup>
                <br/>
                <apex:image styleClass="picklistArrowRight" value="/s.gif">
                    <apex:actionSupport event="onclick" action="{!getSelect}" reRender="abcd"/>
                </apex:image>
                <br/><br/>
                <apex:image styleClass="picklistArrowLeft" value="/s.gif">
                    <apex:actionSupport event="onclick" action="{!getDeselect}" reRender="abcd"/>
                </apex:image>
            </apex:panelGroup>
            <apex:selectList id="sel2" value="{!rightSelected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!SelectedValues}" />
            </apex:selectList>
        </apex:panelGrid>
    </apex:form>
</apex:page>

Output: