Tag Archives: Apex

Select All Fields with SOQL in Apex

Sample Code:

DescribeSObjectResult descResult = Account.getSObjectType().getDescribe();
List<String> fieldList = new List<String>(descResult.Fields.getMap().keySet());

String query = ' SELECT ' + String.join(fieldList, ',') + ' FROM ' + descResult.getName();
List<SObject> records = Database.query(query);

System.debug( records );

Select All Fields with SOQL in Apex by Using Record Id

Sample Code:

Id recordId = '00128000002KuXO';

DescribeSObjectResult descResult = recordId.getSObjectType().getDescribe();
List<String> fieldList = new List<String>(descResult.Fields.getMap().keySet());

String query = ' SELECT ' + String.join(fieldList, ',') + ' FROM ' + descResult.getName() + ' WHERE ' + ' id = :recordId';
List<sObject> records = Database.query(query);

System.debug(records);

Undelete Records in Salesforce Using Batch Apex

Sample Code:

global class AccountUndeleteBatchApex implements Database.Batchable<sObject>{
    
    global Database.queryLocator start(Database.BatchableContext bc){
        String query = 'SELECT Id, Name FROM Account WHERE IsDeleted = True ALL ROWS';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        List<Account> accList = new List<Account>();
        for(Account s:scope){
            //Write your logic
            accList.add(s);
        }
        Undelete accList;
    }
    
    global void finish(Database.BatchableContext bc){
        
    }
}

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