Tag Archives: Apex

Schedule an apex job

To create and test a schedulable class, let’s take a look at how to schedule the class using the user interface.

  1. Create an apex which implemented the schedulable.
    global class TestScheduleService implements Schedulable
    {
        global void execute(SchedulableContext SC)
        {     
            YourServiceClass.serviceExecute();
        }    
    }
    
  2. Your Name -> Setup
  3. App Setup -> Develop -> Apex Classes
  4. Schedule Apex button at the top -> Click Schedule Apex button
  5. Here you can manually schedule an apex class which implemented the schedulable interface.

download

Salesforce Tips & Tricks

  • If you wanted to query ‘accountId, account.name’ fields in a query just specify ‘account.name’ which will retrieve ‘accountId’ automatically.
  • SOQL query can be ORDER BY 32 fields.
  • SOQL/SOSL statements cannot exceed 10,000 characters.
  • SOQL query can’t run more than 120 seconds.
  • For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution times, non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure that the query is selective.
  • The maximum number of records that an event report returns for a user who is not a system administrator is 20000; for system administrators is 100000.
  • Inbound Email Services: Maximum Number of Email Messages Processed (Includes limit for On-Demand Email-to-Case) is number of user licenses multiplied by 1000, up to a daily maximum of 1,000,000.
  • Inbound  Email Services: Maximum Size of Email Message (Body and Attachments) is 10 MB.
  • Apex Limit: Maximum number of characters for a class is 1 million.
  • Apex Limit: Maximum number of characters for a trigger is 1 million.
  • Apex Limit: Maximum amount of code used by all Apex code in an organization1 is 3 MB.
  • Apex Limit: Default timeout of callouts (HTTP requests or Web services calls) in a transaction is 10 seconds.
  • Apex Limit: Maximum size of callout request or response (HTTP request or Web services call) is 3 MB.
  • Apex Limit: Maximum SOQL query run time before the transaction can be canceled by Salesforce is 120 seconds.
  • Apex Limit: Maximum number of class and trigger code units in a deployment of Apex is 5,000.
  • Apex Limit: For loop list batch size is 200.

Compare Old And New Values In Salesforce Trigger

Salesforce provides trigger.oldmap where in all the old records are stored in map with keyset as their ids. We can compare old field value of records with the new values in trigger.

Here in the below example, the trigger compares the account number old value with the new value. If the account number is changed the trigger assigns the type field value “Customer – Direct” else it assigns it a value “Customer – Channel”.

trigger AccountTrigger on Account (before update) {
    
    for (Account acc: Trigger.new) {
        Account oldAccount = Trigger.oldMap.get(acc.Id);
        if(acc.AccountNumber != oldAccount.AccountNumber) {
            System.debug('--Account Number is changed--');
            System.debug('--Old Account Number -' + oldAccount.AccountNumber);
            System.debug('--New Account Number -' + acc.AccountNumber);
            acc.Type = 'Customer - Direct';
        }
        else{
            System.debug('--Account Number has not been updated--');
            acc.Type = 'Customer - Channel';  
        }
    }
}

Clone a Record Using Apex in Salesforce

Salesforce sObjects have a method called clone() which creates a copy of the sObject record. This method has four Boolean type optional parameters.

clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber)

Clone method parameters are as follows:

opt_preserve_id
Type: Boolean
Description: Determines whether the ID of the original object is preserved or cleared in the duplicate. If set to true, the ID is copied to the duplicate. The default is false, that is, the ID is cleared.

opt_IsDeepClone
Type: Boolean
Description: Determines whether the method creates a full copy of the sObject field, or just a reference:
If set to true, the method creates a full copy of the sObject. All fields on the sObject are duplicated in memory, including relationship fields. Consequently, if you make changes to a field on the cloned sObject, the original sObject is not affected.
If set to false, the method performs a shallow copy of the sObject fields. All copied relationship fields reference the original sObjects. Consequently, if you make changes to a relationship field on the cloned sObject, the corresponding field on the original sObject is also affected, and vice-versa. The default is false.

opt_preserve_readonly_timestamps
Type: Boolean
Description: Determines whether the read-only timestamp fields are preserved or cleared in the duplicate. If set to true, the read-only fields CreatedById, CreatedDate, LastModifiedById, and LastModifiedDate are copied to the duplicate. The default is false, that is, the values are cleared.

opt_preserve_autonumber
Type: Boolean
Description: Determines whether auto number fields of the original object are preserved or cleared in the duplicate. If set to true, auto number fields are copied to the cloned object. The default is false, that is, auto number fields are cleared.

Example:

Account acc = new Account(Name = 'Salesforce', Billingcity = 'Texas', Phone = '9999999999');
insert acc;    

//Cloning the above Account Record acc
Account accCloneCopy  = acc.clone(false, false, false, false);
insert accCloneCopy;

Picklist Without None Value in Visualforce Page

Controller:

public class Sample{
    
    public Account acc {get;set;}
    public List<SelectOption> typeOptions {get;set;}
    
    // Constructor called when page is accessed.
    public Sample() {
        
        acc = new Account();        
        typeOptions = new List<SelectOption>();
        
        //Use DescribeFieldResult object to retrieve status field.
        Schema.DescribeFieldResult typeFieldDescription = Account.Type.getDescribe();
        
        //For each picklist value, create a new select option
        for (Schema.PickListEntry pl:typeFieldDescription.getPicklistValues()){
            typeOptions.add(new SelectOption(pl.getValue(),pl.getLabel()));
            
            //Obtain and assign default value
            if (pl.defaultValue){
                acc.Type= pl.getValue();
            }  
        }     
    }
}

Visualforce Page:

<apex:page controller="Sample">
    Please select account type:
    <br/>
    <apex:form >
        <apex:selectList size="1" value="{!acc.Type}">
            <apex:selectOptions value="{!typeOptions}"/>
        </apex:selectList>
    </apex:form>
</apex:page>

Output: