Sales Force Basic Apex Class examples

Apex Class Examples for Salesforce Developer Beginners


1. Insert the account record by receiving the input parameters .

Create new apex class from the Developer Console and enter 'Demo1' for the class name .

Public Class Demo1
{
    Public void CreateAccount(String Name, String Phone){
        account acc=new account();
       
        acc.Name=Name;
       
        acc.phone=Phone;
       
        insert acc;
       
        System.debug('Account Inserted :'+acc.name);
    }
   
}

Demo1 class receives two input parameters (Name&&Phone) ,By using the input parameters CreateAccount method insert the new account record into the sales force database .

Out Put :

/*Go to Developer Console>>Debug>>Open Execute Anonymous Window and execute the following code*/

Demo1 ac= new Demo1();

ac.CreateAccount('testAccount','123456789');

Once the above code executed successfully check the newly created account record from the Accounts Tab .

Note :For test purpose we have used Open Execute Anonymous Window to execute the written codes. Please note that we can also invoke the apex class by using below methods :

  • Apex Trigger .
  • Visualforce Page Controller.
  • Process Buider .
  • Apex methods(Other methods)
  • From External source(eg. By using Rest/Soap integrations)



2.Static Vs Non Static Methods


Public Class Demo2{
    Public static void Method1(){
       
        System.debug('This is static method');
       
    }
   
    Public void method2(){
       
        System.debug('This is Non static method');
       
    }
   
}

Most of the beginners conflict between usage of Static/Non-Static invocation .Demo2 class will explains difference in invoking the Static and non static methods

Out Put :

For static methods we invoke by using class name dot method name directly like below

/*Go to Developer Console>>Debug>>Open Execute Anonymous Window and execute the following code*/

Demo2.Method1();  //Static Method

For Non static methods we invoke them by creating instance of the class like below

Demo2 dm= new Demo2();//Non-Static Method 
dm.Method2();

If you try vice-versa you will receive an error .



3.Retrieving object Records by passing Single field value to the method.

Public class Demo3
{
   
    Public static void FetchAccName(String p) { 
        Set<String> s1= new Set<String>();
       
        List<Account> acc=[Select id, Name From Account where phone=:p];
       
        for(Account a:acc)
           
        {
           
            String s =a.name;
           
            s1.add(s);
           
        }
       
        System.debug('The Account Record Matching the Phone' +s1);
    }
   
}

The FetchAccName method receives phone number as a parameter and search for an account with that number in the existing records.

Out Put :

/*Go to Developer Console>>Debug>>Open Execute Anonymous Window and execute the following code*/

Demo3.FetchAccName('74857937');//Provide phone number which exists in your database .

Once it is executed click on Debug check box for the records which matching the phone number



4. Creation of Account,associated contact and opportunity in single transaction .

Public class Demo5
{
   
   public static void Createrecords(String n)
       
    {
       
        Account a = new Account();
       
        a.Name=n;
       
        insert a;
       
        System.debug('Account :' +a.name);
       
        Contact c = new Contact();
       
        c.LastName='Dinesh';
       
        c.AccountId=a.id;//Id of the Account which we have created above
       
        insert c;
       
        System.debug('Contact :' +c.Lastname);
       
        Opportunity opp= new Opportunity();
       
        opp.Name='Test Opportunity';
       
        Date d= Date.newinstance(2012,2,17);
        opp.CloseDate=d;
        opp.StageName='Closed Lost';
        opp.Accountid=a.id;  //Id of the Account which we have created above
       
        insert opp;
       
        System.debug('Opportunity :' +opp.name);
       
    }
   
}

Createrecords method receives string parameter and creates account ,contact and Opportunity and also associates account with contact and opportunity by using the AccountID .

Out Put :

/*Go to Developer Console>>Debug>>Open Execute Anonymous Window and execute the following code*/

Demo5.Createrecords('Demo5account');   //Invoking the class by passing the parameters.


5. Allowing partial success of the records and storing the records which have failed with errors .


public class Demo5 {
    
    public static void createaccount(List<account> accts){
        List<account> failedList =new List<account>();
        Map<account, String> errorMap =new Map<account, String>();    
        Database.SaveResult[] srList = Database.insert(accts, false);
        
        for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
                System.debug('Successfully inserted account. Account ID: ' + sr.getId());
            }
        }
        //Collecting failed List
        for (Integer i = 0; i < accts.size(); i++) {
            Database.SaveResult s = srList[i];
            account origRecord = accts[i];
            if (!s.isSuccess()) {
                List<Database.Error> e= s.getErrors();  
                errorMap.put(origRecord,e[0].getMessage());
                failedList.add(origRecord);     
            } 
            
        }
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'youremail@email.com'};
            mail.setToAddresses(toAddresses);
            mail.setSubject('Below insertion of the accounts have been failed ');
            mail.setPlainTextBody('Failed Account List'+errorMap);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });   
    }    
}

Demo5 class receives the list of accounts and try to insert them into the database. If the input records are failed to insert then user will get email notification with the failed records list along with the error message.

Out Put :

/*Go to Developer Console>>Debug>>Open Execute Anonymous Window and execute the following code*/

List<account> accts=new List<account>();
for(Integer i=0;i<10;i++) {
    Account a = new Account(Name='TestAccount' + i);
    accts.add(a);
}//Above records will get inserted if your account object does not have any other validations

account acc=new account();
accts.add(acc);//Adding the account without providing the mandatory field(Account Name) .This //record will not be inserted since this does not have mandatory field AccountName .
demo6.createaccount(accts);//Passing the accts list to creteaccount method

If you have mentioned your email in the code ,You would have been received email containing the failed record and error message .

7. Usage of DescribeSObjectResult Class methods .

DescribeSObjectResult Class contains methods for retrieving the sales force object metadata details .

VisualForce Page :


<apex:page controller="Demo8">
  <apex:form >
   <apex:selectlist size="1">
     <apex:selectoptions value="{!options}"></apex:selectoptions>
   </apex:selectlist>
  </apex:form>
</apex:page>

Apex Controller :
    
    public Demo8(){
        
        options = new List<SelectOption>();
        Schema.DescribeSobjectResult r = Account.SobjectType.getDescribe();
        List<Schema.childRelationship> c = r.getChildRelationShips();
        
        for(schema.childRelationship x:c){
            String name = ' '+x.getChildSObject();
            SelectOption op = new SelectOption(name,name);
            options.add(op);
        }    
    }
}

If you run the page it will show you all the child objects of account .You can also use the same logic for custom objects .

*********************************************************************
We hope you are clear with the process now .

If you still require further clarifications,Please let us know in the comments .

Happy Learning☺☺☺


6 comments:

  1. The output for 1st usecase is giving error.
    the acc var does not exists;

    ReplyDelete
    Replies
    1. The output for 1st use-case is giving below error.

      Execute Anonymous Error:

      Line: 2, Column: 1
      Invalid type: AccountCreation

      Delete
  2. Thanks much.this is very useful for beginners..

    ReplyDelete
  3. Please give some more use cases by step by step..i need to learn apex and trigger clearly please help on this

    ReplyDelete
  4. You can also execute 1st usecase in Anonymous window like this
    Demo1.createAccount('Name','Phone');

    ReplyDelete