Category Archives: Salesforce

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 = '';
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');


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'

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.

Test Class for Controller Extension

Apex Extension:

public class AccountExtension  {
    public Account acc {get; set;}
    public AccountExtension(ApexPages.StandardController stdCtrl) {
        //Get Account Id
        Id accountId = stdCtrl.getId();
        //Get Account Required Information
        acc = [SELECT Id, Name, Business_Unit__c, Shipping_Country_Name__c FROM Account WHERE Id = : accountId];

Apex Test Class:

public class TestUtils {
    private static testmethod  void CreateAccount(){
        //Create Account
        Account acc = new Account();
        acc.Name ='Test Account';
        acc.Industry = 'Retail';
        acc.AccountNumber = '123456';
        Insert acc;
        system.assertEquals(true,acc.Id != null);

        //Add Pagereference
        PageReference pageRef = Page.AccountPage;
        //Pass Standard controller Parameter
        pageRef.getParameters().put('Id', String.valueOf(acc.Id));
        String accountId = ApexPages.currentPage().getParameters().get('id');
        system.assertEquals(true, accountId != null);
        ApexPages.StandardController sc = new ApexPages.StandardController(acc);
        AccountExtension accExtn = new AccountExtension(sc);

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"/>

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:


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;
    //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()))
            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:pageblockSection title="Student Details" columns="1" collapsible="false">
                <apex:inputfield value="{!}"/>
                <apex:selectcheckboxes layout="pageDirection"  value="{!MSItems}" label="Interests">                   
                    <apex:selectoptions value="{!getMSPicklist}"/>      
                <apex:commandButton value="Save" action="{!saveStudent}"/>