Sei sulla pagina 1di 73

CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.

com)

Apex Notes Part 1 - By RANJITH KRISHNAN


1. Property in Apex......................................................................................................................................................3
1.1 Example 1 ........................................................................................................................................................3
1.2 Example 2 ........................................................................................................................................................4
1.3 Example 3 ........................................................................................................................................................5
1.4 Example 4 ........................................................................................................................................................5
1.5 Example 5 ........................................................................................................................................................6
2. Accessing objects in apex ........................................................................................................................................7
3. Create record for sObject in Apex ...........................................................................................................................8
3.1 How to insert the changes permanently in object through apex? .................................................................9
4. Exception Handling................................................................................................................................................11
5. How to throw error message from apex to VF page? ...........................................................................................12
5.1 Example .........................................................................................................................................................12
6. How to insert record for related object record? ...................................................................................................13
6.1 Relationship Field names in standard object ................................................................................................14
6.2 Use Case: Create VF page to get account and contacts details. ...................................................................14
7. EXERCISE sObjects in APEX ....................................................................................................................................15
7.1 Exercise - Variable Declaration......................................................................................................................15
7.2 Exercise - Create record in apex and save into database..............................................................................16
7.3 Exercise – Insert parent and related child.....................................................................................................16
8. ARRAYS ..................................................................................................................................................................17
8.1 EXERCISE - ARRAYS ........................................................................................................................................21
8.2 Static Initialization: ........................................................................................................................................21
8.3 ARRAYS IN FOR LOOP ....................................................................................................................................21
8.4 What is for() loop function (Traditional Loop)? ............................................................................................22
8.5 What is ‘For Each’ Loop? ...............................................................................................................................25
8.6 EXERCISE – TRADITIONAL FOR LOOP ............................................................................................................28
8.7 EXERCISE – FOR EACH Loop...........................................................................................................................28
8.8 Array of Sobject Type ....................................................................................................................................28
8.9 EXERCISE – ARRAY of sObject ........................................................................................................................31
8.10 Array of sObject type ....................................................................................................................................32
9. LIST ........................................................................................................................................................................33
9.1 EXERCISE – LIST OF PRIMITIVE TYPE..............................................................................................................38
9.2 LIST OF SOBJECT TYPE ...................................................................................................................................39
10. SET .....................................................................................................................................................................42
11. MAP ...................................................................................................................................................................44
11.1 MULTI-DIMENSIONAL LIST/SET/MAP............................................................................................................49

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 1


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

11.2 EXERCISE – MAP ............................................................................................................................................49


11.3 Use Case 2 .....................................................................................................................................................50
11.4 Map of sObject type: .....................................................................................................................................50
12. How to refer the collection in apex? .................................................................................................................53
12.1 EXERCISE – LIST IN VF AND APEX ..................................................................................................................54
12.2 LIST WITH SIMPLE SOQL ................................................................................................................................56
12.3 EXERCISE – LIST – VF APEX ............................................................................................................................57
12.4 EXERCISE – LIST - SOQL..................................................................................................................................58
13. WHAT IS WRAPPER CLASS ? ..............................................................................................................................60
13.1 VF and APEX Scenario for Wrapper Class......................................................................................................61
13.2 EXERCISE – WRAPPER CLASS - LIST................................................................................................................64
14. Use Cases:..........................................................................................................................................................65
14.1 Use Case 1: Adding data / removing data in list through page .....................................................................65
14.2 Use Case 2: Table with check box for record selection and display selected rows ......................................67
14.3 Use Case 3: Enable or Disable section and render table of data ..................................................................69
14.4 EXERCISE – LIST - ACTIONSUPPORT...............................................................................................................72

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 2


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

1. Property in Apex
What is Property?
It is a class member with key words ‘get’ and ‘set’.

When to use?
 To refer any variable from apex class that should be declared as property.
 To pass value between VF page and apex, the variable in apex should be declared as property.

VF <------------------------------------------> Apex
Pass Values

Examples
public String name {get; set;}

The above variable can now be referred in VF page as {!name}

Purpose of keyword:
get and set keyword defines whether the variable is readable or writeable one.

Keyword to set the accessibility for the variable.


get; => it is readable; to read from apex to vf
set; => it is writeable ; to assign value from vf to apex

public Integer varEditable {get; set;} => read/write


public Integer varReadOnly {get; } => This will not execute ‘Variable is not visible: PropertyDemo.varReadOnly’

In another words.
 When class member is declared with ‘get’ -> the data can be passed from apex to VF.
 When class member is declared with ‘set’ -> the data can be passed/assigned from VF to apex class.

1.1 Example 1
public class PropertyDemo {
public String name {get; set;}
public String city {get; set;}

public PropertyDemo(){
name = 'Ranjith';
city ='Chennai';
}
}

<apex:page controller="PropertyDemo">
Name : {!name} <br/>
City : {!city}
</apex:page>

Note: When VF page executes the class associated with the page will be instantiated automatically.
/apex/propertyDemoPage

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 3


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

PropertyDemo pe = new PropertyDemo();

Output:
Name : Ranjith
City : Chennai
Hence if any variable needs to be initialized when page is loaded, then keep those variable initialization inside the
constructor.
Property can also be written as getter and setter method.
public class PropertyDemo {
public String result {get; set;}
public String city {get; set;}

public String getName(){ //getter method will have return type


return 'Krishnan';
}

public void setCity(String myName){ //setter method will have argument to get value from VF
result = myName;
}
}

1.2 Example 2
public class DemoCollege {
public String collName {get; set;}
public String city {get; set;}
public String branch {get; set;}

public DemoCollege(){
CollName = 'GCT';
city = 'Cbe';
branch ='loly road';
}
}

<apex:page controller="DemoCollege">
College Name : {!CollName} <br/>
City : {!City} <br/>
Branch :{!Branch}
</apex:page>

Example:
<apex:page controller="Demo2">
{!name}
{!age}
</apex:page>

public with class Demo2 {


public string getName(){
return 'Balaji';

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 4


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

}
public integer getAge(){
return 10;
}
}

1.3 Example 3
 Write a class Student with properties name, city, fee
 Intialize the properties inside constructor
 Display the variables in VF page

public Class Student{


public String name {get; set;}
public String city {get; set;}
public Decimal fee {get; set;}

public Student(){
name = 'siva';
city = 'chennai';
fee = 400.50;
}
}

Page:
<apex:page controller="Student">
Name: {!name} <br/>
City : {!city} <br/>
Fee: {!fee}
</apex:page>

1.4 Example 4
public class InputTextExample {
public String name {get; set;}
public Integer age {get; set;}
public String result {get; set;}

public void show(){


result = name + ':' + age;
}
}

<apex:page controller="InputTextExample" >


<apex:form >
<apex:pageBlock title="Form!">
<apex:outputlabel value="Enter Name"></apex:outputlabel>
<apex:inputText value="{!name}"/>
<apex:outputLabel value="Enter Age"></apex:outputLabel>
<apex:inputText value="{!age}"/>

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 5


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

<apex:pageBlockButtons location="top">
<apex:commandButton value="show" action="{!show}"/>
</apex:pageBlockButtons>
</apex:pageBlock>

<apex:pageBlock title="Result" >


{!result}
</apex:pageBlock>
</apex:form>
</apex:page>

1.5 Example 5
Get two numbers from VF page and display addition of two numbers when user clicks on Add button.

Apex Class
public class CalcClass {
public Integer num1 {get; set;}
public Integer num2 {get; set;}
public Integer total {get; set;}

public void add(){


total = num1 + num2;
}

public void multiply(){


total = 0;
total = num1*num2;
}
}

VF Page
<apex:page controller="CalcClass">
<apex:form >
<apex:pageBlock tabStyle="Lead" id="pb">
<apex:pageBlockButtons >
<!-- reRender : it requires id of another component

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 6


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

it is used to refresh the part of the page -->


<apex:commandButton action="{!add}" value="Add" reRender="pb"/>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="1" title="Enter Values">
<apex:pageBlockSectionItem >
<apex:outputLabel >Enter Number 1</apex:outputLabel>
<apex:inputText value="{!num1}"/>
</apex:pageBlockSectionItem>

<apex:pageBlockSectionItem >
<apex:outputLabel >Enter Number 2</apex:outputLabel>
<apex:inputText value="{!num2}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>

<apex:pageBlockSection title="Result">
{!total}
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

2. Accessing objects in apex


What is sObject?
The standard and custom objects in apex programming are called as salesforce objects.

How to refer the salesforce Object in apex?


Syntax:
ObjectName variable;

Example:
Account a;
Contact c;
Opportunity op;

Loan_c ln;
Payment__c py;
Customer__c cust;
Training__c tr;

How to refer the object fields in apex?


Step 1: Allocate memory to the class in the name of object.
Eg., new Account();
Step 2: Then store that reference to a variable to object type.
Eg., Account a = new Account();
Step 3: Using the reference variable, we can refer the object fields like below
Eg., a.Name;
a.Industry;

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 7


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

It means every object in the salesforce data base is considered as class.


Object Class Name
Account -> Account
Lead -> Lead

Customer -> Customer__c (class for a custom object)


Employee -> Employee__c

Account a; // Now the variable a is null


a = new Account(); // allocating memory and the memory reference is stored to variable a
a.Name = 'Ranjith'; //now we can refer the fields of account object and store value
a.AnnualRevenue = 50000;
a.Active__c = 'Yes';

Note: The above variable ‘a’ is a local variable and hence the field values will not be stored into the account object
permanently.

Declare a variable of opportunity type and store values for few of its fields
Opportunity opp = new Opportunity();
opp.Name = 'Test Oppty';
opp.StageName = 'Prospecting';
opp.Amount = 50000;
opp.CloseDate = System.today() + 15;

Declare a variable of Case object type and store values for few of its fields
Case c = new Case();
c.subJect = 'test subject';
c.status = 'new';

Declare a variable of custom object ‘Customer’ and store values for few of its fields
Customer__c cust1 = new Customer();
cust1.last_Name__c = 'Krishnan';
cust1.first_name__c ='Ranjith';

The other format of referring the object fields and assigns the values
Syntax:
ObjectName refVar = new ObjectName(field1=value1, field2=value2...);

Example:
Account a = new Account(Name='test Account', Industry='Energy'); // allowed only for sObject
// OR
Account a = new Account();
a.name='test Account';
a.Industry='Energy';

3. Create record for sObject in Apex


Create a record for contact object using the constructor with parameter and without parameter.
FORMAT 1:

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 8


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Contact c1 = new Contact(lastName = 'Babu', email='test@gmail.com');

FORMAT 2:
Contact c1 = new Contact();
c1.lastName = 'babu';
c1.email = 'test@gmail.com';

FORMAT1 takes only one line of code compared to FORMAT2. So format1 is preferred when we need to create
multiple records.

Hence any format we can use.


Create an account record with name as ‘Capital’ and Industry as ‘Education’
Account a = new Account(Name = ‘Capital’, Industry=’Education’);

Please note that the variable ‘a’ is a local variable and hence the field values will NOT be stored into the account
object.

3.1 How to insert the changes permanently in object through apex?


By using DML statement - insert

insert sObjectVariable;

eg.,
Contact c1 = new Contact();
c1.lastName = 'babu';
c1.email = 'test@gmail.com';
insert c1;

Contact c2 = new Contact(lastName='ramu', phone='1234');


insert c2;

Example:
public class AccountClass {
public String accName {get; set;} public String accIndustry {get; set;}
public Decimal accRevenue {get; set;}

public void createAccount(){


Account a = new Account();
a.Name = accName;
a.Industry = accIndustry;
a.AnnualRevenue = accRevenue;
}
}

VF Page:
<apex:page controller="AccountClass">
<apex:form >
<apex:pageBlock title="Account Entry">
<apex:pageBlockButtons location="top">

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 9


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

<apex:commandButton value="insert" action="{!createAccount}"/>


</apex:pageBlockButtons>
<apex:pageBlockSection columns="1">
<apex:pageBlockSectionItem >
<apex:outputLabel >Enter Account Name</apex:outputLabel>
<apex:inputText value="{!accName}" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Enter Industry</apex:outputLabel>
<apex:inputText value="{!accIndustry}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Enter Revenue</apex:outputLabel>
<apex:inputText value="{!accRevenue}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Example:
public class ApexAccount {
public Account acc {get; set;}
public Contact con {get; set;}
public Position__c pos {get; set;}

public void ceateAccount(){


acc = new Account();
acc.name = 'Sfdcmeet one';
}

public void createContact(){


con = new contact();
con.lastName = 'Krishnan' ;
}

public void createPosition(){


pos = new Position__c();
pos.name = 'Software Engineer';
}
}

VF Page
<apex:page controller="ApexAccount">
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons location="top">
<apex:commandButton value="create Account" action="{!ceateAccount}"/>
<apex:commandButton value="create Contact" action="{!createContact}"/>

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 10


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

<apex:commandButton value="create position" action="{!createPosition}"/>


</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
account Name: {!acc.name} <br/>
contact lastName: {!con.lastname} <br/>
position Name : {!pos.name}
</apex:page>

4. Exception Handling
Exception is nothing but a problem in the program execution. If the problem is not handled and throw the error
properly then the system will throw its own error message. These messages are sometimes difficult to understand
and hence hard to debug. Buy using try catch block we can handle those exception properly and throw custom
messages for a better programming and problem solving.

Example:
try{

} catch(){

} catch(){

} finally{

Example 1:
try {
Account m = new Account();
insert m;
// This doesn't execute since insert causes an exception
System.debug('Statement after insert.');
} catch(DmlException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}

Example 2:
try {
Merchandise__c m = new Merchandise__c();
insert m;
} catch(DmlException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}
// This will get executed
System.debug('Statement after insert.');

Example 3:
try {
Merchandise__c m = new Merchandise__c();

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 11


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

insert m;
} catch(DmlException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}

try {
System.debug('Statement after insert.');
// Insert other records
}
catch (Exception e) {
// Handle this exception here
}

DmlException: Any problem with a DML statement, such as an insert statement missing a required field on a
record.

ListException: Any problem with a list, such as attempting to access an index that is out of bounds

NullPointerException:
Example
String s;
s.toLowerCase(); // Since s is null, this call causes
// a NullPointerException

5. How to throw error message from apex to VF page?


To display error messages in the Visualforce page add below tag where you want to display the error message.
Visualforce page:
<apex:pageMessages />

Apex Controller:
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error Message.');
ApexPages.addMessage(myMsg);

(Or)

ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error Message.'));

5.1 Example
public with sharing class messageCont {
public string name {get; set;}
public string msg;

public void checkName(){


if(name != 'Ranjith'){
msg = 'Name should be Ranjith';
myMessage1(msg);
}
}

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 12


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

public void myMessage1(msg){


ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, msg);
ApexPages.addMessage(myMsg);
}
}
<apex:page controller="messageCont">
<apex:form >
<apex:pageMessages ></apex:pageMessages>
<apex:pageblock >
<apex:commandButton value="checkName" action="{!checkName}"/>
Name: <apex:inputText value="{!name}"/>
</apex:pageblock>
</apex:form>
</apex:page>

6. How to insert record for related object record?


Example: Inserting a contact (child) record for an account (parent)

If the parent and child records need to be inserted, then follow the steps below
Step 1: First insert the parent record
Step 2: Then insert the child record where we need to provide id of the parent record to the relationship field in
child object.

Example 1: Insert Contact for an account


Step 1: Insert parent Record (Account)
Account a = new Account();
a.name = ‘Capital Info’;
a.phone='1234';
a.rating = 'hot';
insert a; // this step will generate 18 digit record id for this record. This id value must be passed to
// the AccountID field in Contact record.

Step 2: Insert child record (contact)


Inserting a contact for the above account (Capital Info)
Contact c1 = new
c1.AccountId = a1.Id; // id of the account record ‘Capital Info’

Example 2: Insert Opportunity for an account


Step 1: Insert account record
Account a = new Account();
a.Name = ‘ABC Corp’;
a.Industry = ‘Finance’;
insert a;

Step 2: Insert Opportunity for the above account


Opportunity op = new Opportunity();
op.Name = ‘Oppty Test’;
op.StageName = ‘Prospecting’;
op.CloseDate = Date.newInstance(2019,10,30);

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 13


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

op.AccountId = a.Id; //id of the account record ‘ABC Corp’


insert op;

In the above cases, the accountID is called Relationship field in child object.

6.1 Relationship Field names in standard object


For standard Object: It is given by salesforce in the below format.
Parent Object Name + word ‘Id’
Eg., AccountID (Account + Id)

Parent Object Child Object RelationshipField


Account Contact AccountId
Case Account AccountId
Case Contact ContactId
Opportunity Account AccountId

6.2 Use Case: Create VF page to get account and contacts details.
Include a button in Vf page to call apex method to insert Account and then insert contact for the same account.
Apex Class:
public class AccountContactCont { // Caps CamelCase
public String accName {get; set;} //small camelCase
public String accRating {get; set;}
public String accIndustry {get; set;}

public String lastName {get; set;}


public String firstName {get; set;}

public void insertAccount(){


Account a = new Account();
a.name = accName;
a.rating = accRating;
a.industry = accIndustry;
insert a;
insertContact(a.Id);
/* Contact c = new Contact();
c.lastName = lastName;
c.firstName = firstName;
c.accountId = a.Id; */
}

public void insertContact(Id accId){


Contact c = new Contact();
c.lastName = lastName;
c.firstName = firstName;
c.accountId = accId;
insert c;
}
}

<apex:page controller="AccountContactCont">
<apex:form >

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 14


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

<apex:pageBlock title="Account Block">


<apex:pageBlockButtons location="top">
<apex:commandButton value="Insert"/>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="1" >
<apex:pageBlockSectionItem >
<apex:outputLabel >Account name</apex:outputLabel>
<apex:inputText value="{!accName}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Account Rating</apex:outputLabel>
<apex:inputText value="{!accRating}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Account Industry</apex:outputLabel>
<apex:inputText value="{!accIndustry}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>

<apex:pageBlock title="Contact Block">


<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel >LastName</apex:outputLabel>
<apex:inputText value="{!lastName}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>
</apex:page>

7. EXERCISE sObjects in APEX


7.1 Exercise - Variable Declaration
1. Declare variable of account type
eg., Account a;

2. Declare variable of contact type


3. Declare variable of custom object Loan
4. Declare variable of custom object Payment
5. Declare variable of custom object Project

Exercise - Access the fields of salesforce object in apex


1. Create an account record in apex
Account a = new Account();
a.Name = 'abc';
a.Rating = 'hot';
a.Industry = 'Energy';

2. Create a contact record in apex.


3. Create a case record in apex.
4. Creata an opportunity record in apex. (closed date as 30 days from today)
5. Create a record for custom object Project (fields Name = 'Insurance Corp', Status__c = 'Open')

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 15


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

6. Create a record for custom Object Loan

7.2 Exercise - Create record in apex and save into database


1. Create an account record in apex and save into database
Account a = new Account();
a.Name = 'abc';
a.Rating = 'hot';
a.Industry = 'Energy';
insert a;

2. Create a contact record in apex and save into database.


3. Create a lead record in apex and save into database.
4. Creata an opportunity record in apex (closed date as 60 days from today) and save into database
5. Create a record for custom object Project (fields Name = 'Insurance Corp', Status__c = 'Open') and save into
database.
6. Create a record for custom Object Loan and save into database.

7.3 Exercise – Insert parent and related child


Create a parent and its child record in apex in same transaction and save into database
1. Insert an account record and contact for the same account.
Account a = new Account();
a.Name = 'abc';
a.Rating = 'hot';
a.Industry = 'Energy';
insert a;

Contact c = new Contact();


c.LastName = 'Krishnan';
c.firstName = 'Ranjith';
c.phone = '1234';
c.accountId = a.Id;
insert c;

2. Insert an account record and two case records for the same account.
Account fields: Name, Rating, Industry, AnnualRevenue
Case fields: subject, status, reason, description, accountId.

3. Insert an account record and two opportunities records for the same account if industry is energy.
Account fields: Name, Rating, Industry, NumberOfEmployees
Opportunity fields: Name, StageName, Amount, CloseDate, accountId

4. Insert a Contact record and two cases for the same contact.
Contact fields: firstName, lastName, Phone, email
Case Fields: subject, status, reason, origin, priority, contactId.

Task Fields
subject : Call Customer 1
status : Not Started
priority : Normal

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 16


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

activityDate : task created date + 3;


whatId :

5. Insert an Opportunity record and a task for the same Opportunity.


Opportunity fields: Name, StageName, Amount, CloseDate, accountId.
Task Fields:
subject : Call Customer 1
status : Not Started
priority : Normal
activityDate : task created date + 3;
whatId :
whoId :

6. Insert an Account record and a task for the same account if industry is finance and
employees > 500.
Account fields: Name, Rating, Industry, NumberOfEmployees.
Task Fields:
subject : Call Customer 2
status : Not Started
priority : Normal
activityDate : task created date + 3;
whatId :
whoId :

7. Insert a lead record and a task for the same lead.


Lead Fields: firstName, lastName, Company, Status (Open - Not Contacted or Working COntacted).
subject : Call Customer 3
status : Not Started
priority : Normal
activityDate : task created date + 3;
whatId :
whoId :

8. Insert a contact record and a task for the same contact.


Contact fields: firstName, lastName, Phone, email.
subject : Call Customer 4
status : Not Started
priority : Normal
activityDate : task created date + 3;
whatId :
whoId :

8. ARRAYS
1. Collection of similar element (same data type)
2. Memory is allocated sequentially (contagiously)
3. Every element is placed in index starting from 0.
0 1 2
-------------------------------------------------
| element 1 | element 2 | element 3 |

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 17


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

-------------------------------------------------
4. It can be of any data type
Primitive (Integer, String, double, date etc.,)
sObject (Account, Contact, Training__C)
User Defined type

Syntax:
dataType[] arrayName; // Integer i; => Integer[] i;

eg., Array Declaration;


Integer[] rollNos;
Integer[] studentIds;
String[] names;
String[] studentNames;
String[] cities;
Double[] salaries;

Account[] accounts;
Contact[] contacts;

Array has fixed number of elements.

Syntax:
dataType[] arrayName = new dataType[3] ;

memory (heap)
0 1 2
-------------------------------
null | null | null |
-------------------------------

Example:
String[] cities = new String[4];
0 1 2 3
-----------------------------
null | null | null | null |
-----------------------------

Dynamic allocation:
cities[0] = 'hyd';
0 1 2 3
-----------------------------
hyd | null | null | null |
-----------------------------

cities[2] = 'chn';
0 1 2 3
-----------------------------
hyd | null | chn | null |
-----------------------------

cities[4] = 'bng'; // out of boundry

Example:
1. Write a array to store names of the students.
String[] studentNames = new String[3];

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 18


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

studentNames[0] = 'Ranjith';
studentnames[1] = 'Ram';

//output
0 1 2
(Ranjith, Ram, null)

2. Declare a array to store city names;


String[] cities = new String[3];

cities[0] = 'hyd';

3. Declare a array to store employeeName;


String[] employeeNames = new String[3] ;

4. Declare a array to store rollNos;


Integer[] rollNos = new Integer[5];
rollNos[0] = 1001;
rollNos[1] = 1002;
rollNos[2] = 1001;
rollNos[3] = 1003;
rollNos[4] = 99;

//Output
(1001, 1002, 1001, 1003, 99)

5. Declare a array to store salaries;


Decimal[] salaries = new Decimal[3];

salaries[0] = 1000;
salaried[1] = 4000;

6. Declare a array to store account records;


Account[] accounts = new Account[3];

7. Declare a array to store contact records;


Contact[] contacts = new Contact[3];

8. Declare a array to store loan__c records;


Loan__c[] loans = new Loan__c[4];

Static Initialization for primitive types:


Integer i = 5;
String name = 'Ranjith';

Static initialization for Array of elements


DataType[] arrayName = new DataType[]{value1, value2}; => 2
DataType[] arrayName = new DataType[]{value1, value2, value3, value4}; => 4

eg.,
String[] name = new String[]{'Ram','Siva','Uma'};
Integer[] rollNos = new Integer[]{1001, 2003, 2002, 4004};

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 19


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Declare
1. Array of salaries with values 4000.00, 500.500, 4005.60
Decimal[] salaries = new Decimal[]{4000.00, 500.500, 4005.60};

2. Array of cities with values 'hyd','chn','dlh','pune'


String[] cities = new String[]{'hyd','chn','dlh','pune'};

3. Array of annualRevenue with values 12000, 340000, 50000


Decimal[] annualRevenues = new Decimal[]{12000, 340000, 50000};

4. Array of productNames with values 'mobile','laptop','mouse'.


String[] productNames = new String[]{'mobile','laptop','mouse'};

How to get the values from array?


String[] cities = new String[]{'hyd','chn','dlh','pune'};

//to get first city name


System.debug('first city name = ' + cities[0]); // hyd

//to get 3 city name


System.debug('3rd city name = ' + cities[2]) ; // dlh

//referring 5th element


System.debug('5th element = ' + cities[4]); //error -> out of boundry

Examples
String[] productNames = new String[]{'mobile','laptop','mouse'};
i. display the 2nd productname
ii. display the 3rd product name.

How to get the size of the array.?


arrayName.size();

System.debug ('total number of productnames ' + productNames.size());

How to get last element?


Integer lastIndexPos = productNames.size() - 1;
productNames.[lastIndexPos];

Declare an array of 5 names.


i. intialize the array with names 'ram', 'siva', 'raju', 'ranjith', 'david'
String[] names = new String[]{'ram', 'siva', 'raju', 'ranjith', 'david'};

ii. display the first name in the log.


names[0];
iii. display the 3rd name in the log.
names[2];
iv. display the total number of names in the array
names.size();
v. display the last name in the array.
names[ names.size() - 1 ];

Note:
Reading element in array is faster compared to primitive type.
It is locatiing the element based on index in the sequential memory stack.
Similar to locating a page in a book based on index.

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 20


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

8.1 EXERCISE - ARRAYS


1. Write a array to store names of the students.
String[] studentNames = new String[3];

studentNames[0] = 'Ranjith';
studentnames[1] = 'Ram';

2. Declare a array to store city names;


3. Declare a array to store employeeName;
4. Declare a array to store rollNos;
5. Declare a array to store salaries;
6. Declare a array to store account records;
7. Declare a array to store contact records;
8. Declare a array to store loan__c records;

8.2 Static Initialization:


DataType[] arrayName = new DataType[]{value1, value2}; => 2
DataType[] arrayName = new DataType[]{value1, value2, value3, value4}; => 4

eg.,
String[] name = new String[]{'Ram','Siva','Uma'};
Integer[] rollNos = new Integer[]{1001, 2003, 2002, 4004};

Declare
1. Array of salaries with values 4000.00, 500.500, 4005.60
2. Array of cities with values 'hyd','chn','dlh','pune'
3. Array of annualRevenue with values 12000, 340000, 50000
4. Array of productNames with values 'mobile','laptop','mouse'.

Exercise
String[] productNames = new String[]{'mobile','laptop','mouse'};
i. display the 2nd productname
ii. display the 3rd product name.

How to get the size of the array.?


How to get last element?

Declare an array of 5 names.


i. intialize the array with names 'ram', 'siva', 'raju', 'ranjith', 'david'
ii. display the first name in the log.
iii. display the 3rd name in the log.
iv. display the total number of names in the array
v. display the last name in the array.

8.3 ARRAYS IN FOR LOOP


Declare an array to store salary details

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 21


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

4000, 5000, 3000

Decimal[] salaries = new Decimal[]{4000, 5000, 3000};

Declare an array to store the city names.


Hyd, Chn, pune

String[] cities = new String[] {'Hyd','Chn', 'Pune'};

Display the first city in the log.


System.debug(cities[0]);

Get the last city name;


System.debug(cities[2]);

System.debug(cities.size());

Let’s see how to display the array element into the log one by one.
String names = new String[]{'aaa','bbb','ccc','ddd','eee','fff'};

To do this, we need to iterate the array names using for() loop function

8.4 What is for() loop function (Traditional Loop)?


Syntax:
for( intialization; exit-condition ;increment/decrement){
//logic
}

Example:
Display number 1 to 10 in the log
for(Integer i = 1 ; i < 11; i = i + 1){
System.debug(i);
}

How it works?
Step 1: Variable i is initialized with 1, then execute the logic only if the exit_condition is true.
Step 2: Increment the variable i to i + 1, then execute the logic only if exit condition is true.

Initialization condition (i < 11) Logic (System.debug(i)) increments (i = i +1)


i = 1; 1 < 11 (true) 1 i = 1 + 1 (2)
i=2 2 < 11 (true) 2 i = 2 + 1 (3)
.
.
i = 11 11 < 11 (false)

Example: Print 5 to 20 in the log;


for(Integer i = 5; i < 21; i++){
System.debug(i);
}

Example: Print 10 to 100 in the log


for(Integer i = 10; i < 101; i++){
System.debug(i)
}

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 22


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Example: Print 10 to 1 in the log


for(Integer j = 10; j > 0; j = j - 1){
System.dbug(j)
}

Example: Print 2,4,6....50


for(Integer i = 2; i < 51; i = i +2){
System.debub(i)
}

Example: Print 30 to 1 in the log.


Print odd numbers from 1 to 10; (1, 3, 5, 7, 9)
for(Integer i = 1; i < 10; i = i + 2){
System.debug(i);
}

i=1
for(
1
)

i=3 i = 3 ( i < 10) true


for{
3
}
.
.
.
i=9 i = 9 + 3; ( 11 < 10) false

Infinite loop (endless): This is an incorrect looping example.


for(Integer i = 1; i > 5; i++){
System.debug(i);
}
Note: Make sure the loop ends without going in infinite loop.

Print the array of city names one by one in the log


String[] cities = new String[]{'hyd','chn','pune','bng','dlh'};

0 1 2 3 4
---------------------------------------------
| hyd | chn | pune | bng | dlh |
---------------------------------------------
cities.size() => 5

//cities[index] ; // index starts from 0


5
for(Integer i = 0; i < cities.size(); i++) {
System.debug(cities[i]); // hyd
}

1. Declare the array of names 'raj','ranjith','swetha','kiran' and display in the log one by one.
String[] names = new String[]{'raj','ranjith','swetha','kiran'};
for(Integer i = 0; i < names.size(); i++){
System.debug('name : ' + names[i]);
}

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 23


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

2. Declare array to store the productNames 'laptop','mouse','keyboard','system' and display in the log one by
one.
String productNames = new String[]{'laptop','mouse','keyboard','system'};

for(Integer i = 0; i < productNames.size(); i++){


System.debug('product name : ' + productNames[i]);
}

3. Declare the course names 'sfdc','java','dotnet','devops' and display in the log one by one from the second
element
String[] courses = new String[]{'sfdc','java','dotnet','devops'};
for(Integer i = 1; i < courses.size(); i++ ){
System.debug(courses[i]);
}

4. Declare array to store the industry values such as 'energy','apparel','education','technology' and display the
industry only if it belongs to energy
String[] industries = new String[]{'energy','apparel','education','technology'};
for(Integer i = 0; i < industries.size(); i++){
if(industries[i] == 'energy')
System.debug('Industry is ' + Industries[i]);
}

5. Declare an array to store salaries and sum up all the salaries, then display the total salary in the log.
Decimal[] salaries = new Decimal[]{4000,4000,5000, 3000, 6000, 8000};

//display the salary one by one


for(Integer i = 0; i < salaries.size(); i++){
System.debug(salaries[i]);
}

i = 0 (index = 0)
for{
Integer j ; //null
j = j + i;
}

i = 1;
for{
Integer j/null
j = null + 4000;
}

Integer totalSalary = 0;
for(integer i = 0; i < salaries.size(); i++){
totalSalary = totalSalary + salaries[i];
}
//{4000,4000,5000, 3000, 6000, 8000};

i=1 totalSalary
for{
totalSalary = 0 + 4000; 4000
}

i = 2;

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 24


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

for{
totalSalary = 4000 + 4000; 8000
}

i = 3;
for{
TotalSalary = 8000 + 5000; 13000
}

Example: Decimal[] salaries = new Decimal[]{4000,4000,5000, 3000, 6000, 8000};


Decimal totalSalary = 0;
for(integer i = 0; i < salaries.size(); i++){
totalSalary = totalSalary + salaries[i];
}
System.debug('total Salary ' + totalSalary);

Example :Declare an array to store annualRevenues such as 30000, 40000, 50000, 30000 and display the total in
the log.
Decimal[] annualRevenues = new Decimal[]{30000, 40000, 50000, 30000};
Decimal totalRevenues = 0.0;
for(Integer i = 0; i < annualRevenues.size(); i++){
totalRevenues = totalRevenues + annualRevenues[i];
}
System.debug(totalRevenues);

Similarly the array can also be iterated using another format of for looping called ‘For Each’ Loop

8.5 What is ‘For Each’ Loop?


Syntax:
for(variable : arrayName ){
//logic
}

Where, arrayName => name of the array


Variable => variable declaration of array data type.

Example:
String[] industries = new String[]{'energy','apparel','education','technology'};
arrayName : array name is industries
variable : String a

for(String i : industries){
System.debug(i); // energy i => 0
}

Output:
energy
apparel
education
technolgy

How it works?
Iteration 1: 1st element from array will be copied to variable i and execute the logic
Iteration 2: 2nd element from array will copied to variable i and execute the logic
The above step continues till to the last element of the array and the control will come out from the loop.

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 25


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Hence, we need not initialize the counter and initialize like in the case of traditional for loop.
Example:

Example: Decimal[] annualRevenues = new Decimal[]{30000, 40000, 50000, 30000};


0 1 2 3
----------------------------------------------
30000 | 40000 | 50000 | 30000
--------------------------------------------

i = i + 1;
for(Decimal d : annualRevenues ){
System.debug(d) ;
}

loop 1 :
d = 30000

loop 2;
d = 40000

loop 3;
d = 50000

loop 4;
d = 30000;

for each loop


no increment
no exit condition check;

Example: Decimal[] annualRevenues = new Decimal[]{30000, 40000, 50000, 30000};


i. Display the total revenues
Decimal totalRevenues = 0.0;
for(Decimal d : annualRevenues ){
totalRevenues = totalRevenues + d ;
}

iteration 1 => d = 30000


interation 2 => d = 40000

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 26


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Example: Declare the array to store the rollNo such as 1001, 2002, 3003, 4004, 5005 and display it one by one in
the log.
Integer[] rollNos = new Integer[] {1001, 2002, 3003, 4004, 5005};
for(Integer i : rollNos){
System.debug(i);
}

Example: Declare the array of integers such as 5,9,10,23,40


Integer[] numbers = new Integer[]{5,9,10,23,40};

for(Integer i : numbers){
System.debug(i);
}

i. Sum up all the numbers


Integer[] numbers = new Integer[]{5,9,10,23,40};

Integer total = 0;
for(Integer i : numbers){
total = total + i;
}
System.debug('total ' + total);

Example: Declare the array of salaries such as 1000,5000, 4000, 6000


i. display the salary in the log one by one
ii. sum up all the salaries and display the total

Decimal[] salaries = new Decimal[]{1000, 5000, 4000, 6000};


Decimal totalSalaries = 0.0;

for(Decimal d : salaries) {
System.debug(d);
totalSalaries = totalSalaries + d;
}
System.debug(totalSalaries);

Example: Declare the array of industries such as 'energy' 'education', 'apparel', 'technology';
i. display the industry value only if it is 'apparel'

String[] industries = new String[]{'energy' 'education', 'apparel', 'technology'} ;

for(String i: industries){
if(i == 'apparel )
System.debug(i);
}

Example: Declare the array of status such as 'open', 'closed', 'new'


display the status only it it is closed.

String[] statuses = new String[]{'open', 'closed', 'new'};


for(String s: statuses) {
if(s == 'Closed')
System.debug( 'the status is ' + s);
}

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 27


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

8.6 EXERCISE – TRADITIONAL FOR LOOP


1. Declare an array to store salary details
4000, 5000, 3000
2. Decimal[] salaries = new Decimal[]{4000, 5000, 3000};
3. Declare an array to store the city names.
Hyd, Chn, pune
i. Display the first city in the log.
ii. Get the last city name;

4. Display number 1 to 10 in the log

5. Print 5 to 20 in the log;


6. Print 10 to 100 in the log
7. Print 10 to 1 in the log
8. Print 2,4,6....50
9. Print 30 to 1 in the log.
10. Print odd numbers from 1 to 10;
11. Print the city name one by one in the log
12. Declare the array of names 'raj','ranjith','swetha','kiran' and display in the log one by one.
13. Declare array to store the productnames 'laptop','mouse','keyboard','system' and display in the log one by one.
14. Declare the course names 'sfdc','java','dotnet','devops' and display in the log one by one from the second
element
15. Declare array to store the industry values such as 'energy','apparel','education','technology' and display the
industry only if it belongs to energy
16. Declare an array to store salaries and sum up all the salaries, and then display the total salary in the log.
17. Sum up all the values.
Decimal[] salaries = new Decimal[]{4000,4000,5000, 3000, 6000, 8000};

8.7 EXERCISE – FOR EACH Loop


1. Declare an array to store annualRevenues such as 30000, 40000, 50000, 30000 and display the total in the log.
2. Declare an array to store industries such as 'energy','apparel','education','technology' and display each industry
value one by once in the log.
3. Decimal[] annualRevenues = new Decimal[]{30000, 40000, 50000, 30000};
Display the total revenues
4. Declare the array of employee names and display in the log one by one using for each loop
5. Declare the array of policyNames such as 'life ins' 'health', 'accidental', 'group' and disply the policy names one
by one in the log.
6. Declare the array to store the rollNo such as 1001, 2002, 3003, 4004, 5005 and display it one by one in the log.

8.8 Array of Sobject Type


================================================
sObject => the salesforce objects in API is called as sObject
=================================================
Account a = new Account();
a.Name = 'test';

Contact c = new Contact();


c.lastName = 'krishnan';

Integer[] rollNos = new Integer[5];

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 28


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

0 1 2 3 4
--------------------------------------------------------
| null | null | null | null | null |
--------------------------------------------------------
rollNos[0] = 3;
rollNos[1] = 4;

Account[] accs = new Account[3];


0 1 2
----------------------------------------------
null | null | null |
----------------------------------------------
Account a Account b Account b

Account a = new Account();


a.Name = 'test';
accs[0] = a;

Account a1 = new Account();


a1.Name = 'test 1';
accs[1] = a1;

Example: Declare the array of contacts and insert 3 contacts records into the array.
Contact[] contacts = new Contact[3];
Contact c1 = new Contact();
c1.lastName = 'krishnan';
c1.firstName = 'Ranjith';

Contact c2 = new Contact();


c2.lastName = 'kumar';
c2.firstName = 'suresh';

Contact c3 = new Contact();


c3.lastName = 'reddy';
c3.firstName = 'swetha';
contacts[0] = c1;
contacts[1] = c2;
contacts[2] = c3;

(Contact:{LastName=krishnan, FirstName=Ranjith}, => 0


Contact:{LastName=kumar, FirstName=suresh}, => 1
Contact:{LastName=reddy, FirstName=swetha}) => 2

Example: Declare the array of opportunity and store 3 opportunities with below values
Name StageName CloseDate Amount
aaa Prospecting today() 5000
bbb Closed Won today() 6000
ccc Closed Lost today() 0

Opportunity[] opportunities = new Opportunities[3];

Opportunity op1 = new Opportunity();


op1.Name= 'aaa';
op1.StageName = 'Prospecting';
op1.CloseDate = System.today();
op1.Amount = 5000;

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 29


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Opportunity op2 = new Opportunity();


op2.Name= 'bbb';
op2.StageName = 'Closed Won';
op2.CloseDate = System.today();
op2.Amount = 6000;

Opportunity op3 = new Opportunity();


op3.Name= 'ccc';
op3.StageName = 'Closed Lost';
op3.CloseDate = System.today();
op3.Amount = 0;
opportunities[0] = op1;
opportunities[1] = op2;
opportunities[2] = op3;

Example: Declare the array of case records to store 3 case records as below
subject status
test 1 open
test 2 closed
test 3 new
i. display the subject of the case one by one in the log
ii. display the status of the case one by one in the log

Case[] cases = new Case[3];


Case c1 = new Case(subject = 'test 1', status = 'open');
Case c2 = new Case(subject = 'test 2', status = 'closed');
Case c3 = new Case(subject = 'test 3', status = 'new');
cases[0] = c1;
cases[1] = c2;
cases[2] = c3;

OR
Case c1 = new Case(subject = 'test 1', status = 'open');
Case c2 = new Case(subject = 'test 2', status = 'closed');
Case c3 = new Case(subject = 'test 3', status = 'new');
Case[] cases = new Case[]{c1, c2, c3};

Example: Declare the array of lead records to store 4 lead records as below
name rating phone
aaa hot 123
bbb warm 345
ccc cold 234
ddd hot 236
Lead l1 = new Lead(name='aaa', rating='hot', phone='123');
Lead l2 = new Lead(name='bbb', rating='warm', phone='345');
Lead l3 = new Lead(name='ccc', rating='cold', phone='234');
Lead l4 = new Lead(name='ddd', rating='hot', phone='236');
Lead[] leads = new Lead[]{ l1,l3, l2, l4};

i. display the lead record one by one


for(Lead l : leads){
System.debug(l);
}

ii. store the lead record into another variable if rating is cold.

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 30


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Lead ld;
for(Lead l : leads){
if(l.rating == 'cold)
ld = l;
}

iii. display the lead name and the phone in the log if rating is hot
for(Lead l : leads){
if(l.rating == 'hot')
System.debug('name ' + l.name + ':: phone ' + l.phone );
}

Example: Create 3 opportunity records and initialize the array of opportunities


Name StageName CloseDate Amount
aaa Prospecting today() 5000
bbb Closed Won today() 6000
ccc Closed Lost today() 0

Opportunity op1 = new Opportunity();


op1.Name= 'aaa';
op1.StageName = 'Prospecting';
op1.CloseDate = System.today();
op1.Amount = 5000;

Opportunity op2 = new Opportunity();


op2.Name= 'bbb';
op2.StageName = 'Closed Won';
op2.CloseDate = System.today();
op2.Amount = 6000;

Opportunity op3 = new Opportunity();


op3.Name= 'ccc';
op3.StageName = 'Closed Lost';
op3.CloseDate = System.today();
op3.Amount = 0;

//static initialization
Opportunity[] opps = new Opportunity[]{op1, op2, op3};

//sum up the entire opportunity amount


Decimal totalValue = 0.0;
for( Opportunity o: opps ) {
totalValue = totalValue + o.Amount;
}

//sum up the entire opportunity amount if opportunity is closed


Decimal totalClosed = 0.0;
for(Opportunity o1 : opps){
if(o1.StageName == 'Closed Won' || o1.StageName == 'Closed Lost')
totalClosed = totalClosed + o1.Amount;
}

8.9 EXERCISE – ARRAY of sObject


For each loop

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 31


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Example 1: Declare the array of names and store the values 'aaa',''bbb',''ccc', 'ddd'

String[] names = new String[]{'aaa',''bbb',''ccc', 'ddd'};

for(String s: names){

System.debug(s);

Exercise 1: Declare the array of integers such as 5,9,10,23,40

i. Display the number one by one in the log

ii. Sumup all the numbers

Exercise 2: Declare the array of salaries such as 1000,5000, 4000, 6000

i. display the salary in the log one by one

ii. sum up all the salaries and display the total

Exercise 3: Declare the array of industries such as 'energy' 'education', 'apparel', 'technology';

i. display the industry value only if it is 'apparel'.

Exercise 4: Declare the array of status such as 'open', 'closed', 'new'

i. display the status only it it is closed.

8.10 Array of sObject type


=========================================================

sObject => The salesforce objects in API is called sObject

=========================================================

Exercise 1: Declare the array of contacts and insert 3 contacts records into the array.
Exercise 2: Declare the array of opportunity and store 3 opportunities with below values
Name StageName CloseDate Amount
aaa Prospecting today() 5000
bbb Closed Won today() 6000
ccc Closed Lost today() 0

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 32


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Exercise 3: Declare the array of case records to store 3 case records as below
subject status
test 1 open
test 2 closed
test 3 new
i. display the subject of the case one by one in the log
ii. display the status of the case one by one in the log

Exercise 4: Declare the array of lead records to store 4 lead records as below
name rating phone
aaa hot 123
bbb warm 345
ccc cold 234
ddd hot 236
i. display the lead record one by one
ii. store the lead record into another variable if rating is cold.
iii. display the lead name and the phone in the log if rating is hot

Exercise 5: Create 3 opportunity records and initialize the array of opportunities


Name StageName CloseDate Amount
aaa Prospecting today() 5000
bbb Closed Won today() 6000
ccc Closed Lost today() 0
i. sum up all the opportunity amount
ii. sum up all the opportunity amount if opportunity is closed

9. LIST
List : collection of ordered elements
Elements are located based on index
It can accept duplicate elements
Size of the list will be increased when adding elements
will be decreased when elements are removed.

The order we insert is maintained.


It can be of primitive or reference (sObject, user-defined (apex class), collection)

Syntax:
List<DataType> listName; // dataType[] arrayName;

Example:
List<Integer> numbers;
List<String> names;
List<Decimal> salaries;

List<Account> accounts;
List<Contact> contacts;
List<Loan__c> loans;

Initialization:

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 33


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

List<Integer> numbers = new List<Integer>();


ClassName refvar kw Constructor

Declare a list of salaries and allocate memory


List<Decimal> salaries = new List<Decimal>();

List of cities
List<String> cities = new List<String>();

List of account records


List<Account> accList = new List<Account>();

List is a predefined class


It has 3 constructors
List<DataType> listName = new List<DataType>();
List<DataType> listName = new List<DataType(AnotherList);
List<DataType> listName = new List<DataType(AnotherSet);

How to add element into list?


Using instance methods of List class.

1. add(element); //to add element into the list


List<String> cities = new List<String>();
cities.add('hyd');
0
--------------
| hyd |
------------
cities.add('chn');
0 1
--------------------------
| hyd | chn |
--------------------------

add more city such as pune, dlhi, noida, bngl


cities.add('pune');
cities.add('dlhi');
cities.add('noida');
cities.add('bnlg');
0 1 2 3 4 5
-----------------------------------------------------------------
| hyd | chn | pune | dlhi | noida | bngl |
-----------------------------------------------------------------
System.debug('cities :: ' + cities);

Output:
cities :: (hyd, chn, pune, dlhi, noida, bnlg)

2. get(index) => to get the element from list based on specified index.

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 34


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

eg.,
//get 1st city name
String city = cities.get(0);
System.debug('1st city value : ' + city);
//3 city name
System.debug('3rd city name : ' + cities.get(2));

Declare a list to store employee names and add 5 employee names.


Then display the 4th employee name in the log.

List<String> employees = new List<String>();


employees.add('ram');
employees.add('siva');
employees.add('reddy');
employees.add('ranjith');
employees.add('shravya');
//get 4th employee
System.debug('4th employee in the list : ' + employees.get(3) );

3. remove(index) => to remove the element from the list based on index
0 1 2 3 4
----------------------------------------------------
| ram | siva | reddy | ranjith | shravya |
-----------------------------------------------------

Remove the 2nd employee from the list employees


employees.remove(1);
0 1 2 3
------------------------------------------------
| ram | reddy | ranjith | shravya |
------------------------------------------------

remove the 2nd employee


employees.remove(1);
0 1 2
-------------------------------------
| ram | ranjith | shravya |
-------------------------------------

How to initialize the list while declaring?


List<dataType> listName = new List<dataType>{value1, value2, value3....};

Example:
Declare list of productNames and initialize with 5 products

List<String> productName = new List<String>{'prod1','prod2','prod3','prod4','prod5'};


System.debug(productName);

Example: Write list of coursenames and initialize with 5 different coursenames

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 35


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

List<String> courseNames = new List<String>{'sfdc admin','sfdc dev','banking','Ins','jave'};

4. Size() to get the size of the list (number of elements in the list)
List<String> courseNames = new List<String>{'sfdc admin','sfdc dev','banking','Ins','java'};
Integer count = courseNames.size();
System.debug(count);

// add another course - bpo


courseNames.add('bpo');
System.debug('count after added BPO :: '+ courseNames.size());

5. Inserting based on index


add(index, element)

List<Integer> empNos = new List<Integer>{1001, 2002, 3003, 4004, 5005};


0 1 2 3 4
---------------------------------------------------
| 1001 | 2002 | 3003 | 4004 | 5005 |
--------------------------------------------------

//add - 2055
empNos.add(2055);
0 1 2 3 4 5
------------------------------------------------ ---------
| 1001 | 2002 | 3003 | 4004 | 5005 | 2055 |
----------------------------------------------------------

// add - 3055 as 2nd element


empNos.add(1,3055); //will add in the specified index 1

0 1 2 3 4 5 6
------------------------------------------------ --------------------
| 1001 | 3055 | 2002 | 3003 | 4004 | 5005 | 2055 |
----------------------------------------------------------------------

6. Replacing the element


set(index, element)
//replace the 2nd employee no with 999
empNos.set(1,999);
System.debug('after replaced 3055 with 999 ' + empNos);

7. Clear the list


clear();
empNos.clear();

8. isEmpty() //to check if the list is empty


// isEmpty() => this method will return true when list has not element
// => returns false when list contains any element
Example

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 36


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Boolean flag = empNos.isEmpty();


System.Debug('no elements in empNos, true or false?? ' + flag);
if(empNos.isEmpty())
System.debug('no employess');
else
System.debug('employee exists');

List<String> courseNames = new List<String>{'sfdc admin','sfdc dev','banking','Ins','java'};

9. contains(element) => this return true if the argument present in the list
Check if banking course exists or not

If(courseNames.contains('banking'))
System.debug('yes it is available');
else
System.debug('no banking course now!');

10. addALL(list) to add one list to another


List<Integer> studentNos1 = new List<Integer>{10,30,40,50};
List<Integer> studentNos2 = new List<Integer>{11,23,33,44};

//adding all the studentNos1 to studentNos2


studentNos2.addAll(studentNos1);
System.debug(studentNos2);

For Each Loop:


List<String> courseNames = new List<String>{'sfdc admin','sfdc dev','banking','Ins','java'};
display course name one by one in the log

for(variable : array/list/set){
//logic
}

for(String c : courseNames ){
System.debug(c);
}

11. IndexOf(element) to get the index position of student no '33'


Integer ind = StudentNos2.indexOf(33) + 1;
System.debug('Position of student no 33 :: ' + ind );

12. sort() to sort the elements in the list


List<Integer> studentNos1 = new List<Integer>{10,30,40,50};
List<Integer> studentNos2 = new List<Integer>{11,23,33,44};

//adding all the studentNos1 to studentNos2


studentNos2.addAll(studentNos1);
System.debug(studentNos2);

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 37


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

//get the index position of student no '33'


Integer ind = StudentNos2.indexOf(33) + 1;
System.debug('Position of student no 33 :: ' + ind );

studentNos2.Sort();
System.debug('after sorted:: ' + studentNos2);

Instance Methods of LIST


Adding element : add(element)
Adding element based on index : add(Index, element)
Remove element : remove(index)
size of the list : size()
Replace element : set(index, element)
To check if list is empty : isEmpty()
to check if element exists : contains(element)
To add one list to another : addAll(list)
To sort the list : sort()
To get element : get(index)

List<String> cities = new List<String>{'hyd','chn','pune','noida'};


for(String c :cities){
System.debug(c);
}

9.1 EXERCISE – LIST OF PRIMITIVE TYPE


1. Write the syntax for a List declaration.
2. Declare a list that can store integer values.
a. Add the values 10,30,30,2,3,125, 88, 99 and get the size of the list.
b. Remove the 2nd and 5th element of the list using list method.
c. Get the 4th element of the list.
d. Replace the last instance of '125' with '100'
e. Sort the list (which is allowed only for primitive types)
f. How to initialize a list while declaring?

3. Declare a list of salaries and allocate memory


4. Declare list of account records

5. Declare List of cities


a. Add cities such as ‘hyd’,’chn’,’pune’,’dlhi’,’noida’
b. Display the list in the log
c. Display 1st city name in the log
d. Display the 3rd city name in the log

6. Declare a list to store employee names and add 5 employee names.


a. Then display the 4th employee name in the log.
b. Remove the 2nd employee from the list employees, then display the list in the log

7. Declare list of productNames and initialize with 5 products

8. Write list of coursenames and initialize with 5 different coursenames


Course Names are ;sfdc admin','sfdc dev','banking','Ins' and'java’;

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 38


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Display the size of the list (number of elements in the list) in the log
a. Add another course – bpo and display in the log.

9. List<Integer> empNos = new List<Integer>{1001, 2002, 3003, 4004, 5005};


a. Add employee no 2055 and display the employees in the log.
b. Add an employee no 3055 in the index 1 and display the employees in the log
c. Replace the 2nd employee no with 999 and display the employees in the log
d. Remove all the employee nos
e. Check if the employees list is empty or not.

10. List<String> courseNames = new List<String>{'sfdc admin','sfdc dev','banking','Ins','java'};


a. Check if the banking course exists or not. If course exists then display as ‘it is available' else ‘not
available’ in the log.
11. List<Integer> studentNos1 = new List<Integer>{10,30,40,50};
List<Integer> studentNos2 = new List<Integer>{11,23,33,44};
a. Add all the elements from studentNos1 to studentNos2
12. List<String> courseNames = new List<String>{'sfdc admin','sfdc dev','banking','Ins','java'};
a. display course name one by one in the log
b. display the index position of course name banking
c. Sort the course names

9.2 LIST OF SOBJECT TYPE


Array:
Account[] accounts = new Account[3];
Account a1 = new Account(Name='test1');
Account a2 = new Account(name='test 2');
accounts[0] = a1;
accounts[1] = a2;

List<Account< accounts = new List<Account>();


Account a1 = new Account(Name='test 1', Industry='Energy');
Account a2 = new Account(Name ='test2', Industry='Education');
accounts.add(a1);
accounts.add(a2);

1. Declare the list of opportunities and store 3 opportunity records as below


Name Amount StageName CloseDate
Opty1 10000 Closed Won 2019-10-30
Opty2 2000 Prospecting 2019-10-25
Opty3 0 Closed Lost today

List<Opportunity> oppList = new List<Opportunity>();


Opportunity op1 = new Opportunity();
op1.Name = 'Opty1';
op1.Amount = 10000;
op1.StageName = 'Closed Won';
op1.CloseDate = Date.newInstance(2019,10,30);

Opportunity op2 = new Opportunity();


op2.Name = 'Opty2';
op2.Amount = 2000;
op2.StageName = 'Prospecting';

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 39


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

op2.CloseDate = Date.newInstance(2019,10,25);

Opportunity op3 = new Opportunity(Name='Opty3', Amount=0, StageName='Closed Lost',


CloseDate=System.today());
oppList.add(op1);
oppList.add(op2);
oppList.add(op3);
0 1 2
------------------------------
| op1 | op2 | op3 |
------------------------------
i. get the 1st opportunity from the oppList and store into another variable
Opportunity o1 = oppList.get(0);

ii. get the 3rd element from the oppList


Opportunity o2 = oppList.get(2); // o2 = (name =Opty2,Amount= 2000,StageName=Prospecting, CloseDate=
// 2019-10-25) ;
String opName = o2.Name;
Decimal opAmount = o2.Amount;
String opIndustry = o2.StageName;
Date opCloseDate = o2.CloseDate;

iii. display opportunity record in the log one by one from the oppList
for(Opportunity o: oppList) {
System.debug(o);
}

iv. display each opportunity name in the log


for(Opportunity o: oppList) {
System.debug(o.Name);
}

v. display each opportunity amount in the log


for(Opportunity o: oppList) {
System.debug(o.Amount); // o = op1 (Name=, stagename, amount, closedate)
System.debug(o.type); //it is not possible
}

vi. sum up all the opportunity amount


Decimal totalAmount = 0.0;
for(Opportunity o: oppList){
totalAmount = totalAmount + o.Amount;
}

vii. get all the opportunity names from the oppList and store into another collection
List<String> oppNames = new List<String>();
for(Opportunity o : oppList){
String nme = o.Name;
oppNames.add( nme );
}

viii. store the opportunity names into another collection only if amount is greater than 0
List<String> oppNames = new List<String>();

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 40


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

for(Opportunity o : oppList){
if(o.Amount > 0)
oppNames.add(o.Name);
}

ix. Sum up all the opportunities amount if close date is today and display the total amount in the log.
Decimal totalValue = 0.0
for(Opportunity o: oppList){
if(o.CloseDate == System.today())
totalValue = totalValue + o.Amount;
}
System.debug(totalValue);

2. Create 3 case records as below and store (initialize) into list of case
Subject Status Origin
Case1 Open Web
Case2 Open Email
Case3 Escalated Phone

Case c1 = new Case(subject='Case1', status='Open', Origin='Web');


Case c2 = new Case();
c2.subject = 'Case2';
c2.status = 'Open';
c2.origin = 'Email;

Case c3 = new Case(subject='Case3', status='Escalated', origin='Phone');


List<Case> cases = new List<Case>{c1, c2, c3};

3. Create 3 lead records and store into list of lead


lastName Company LeadSource AnnualRevenue
aaa comp1 email 10000
bbb comp2 phone 15000
ccc comp3 email 5000
Lead l1 = new Lead(lastName = 'aaa', Company ='comp1', leadSource='email', AnnualRevenue=10000);
Lead l2 = new Lead(lastName = 'bbb', Company ='comp2', leadSource='phone', AnnualRevenue=15000);
Lead l3 = new Lead(lastName = 'ccc', Company ='comp3', leadSource='email', AnnualRevenue=5000);

List<Lead> leads = new List<Lead>{l1, l2, l3};

i. Display each lead record one by one in the log


for(Lead l :leads ){
System.debug(l);
}

ii. Display the lead lastName one by one in the log


for(Lead l : leads){
System.debug('Last Name :: ' + l.lastName);
}

iii. Sum up annual revenue of all the lead records


Decimal leadRevenues = 0.0
for(Lead l : leads){
leadRevenues = leadRevenues + l.AnnualRevenue;
}

iv. Get all the company names into another collection if lead source is email.

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 41


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

List<String> compNames = new List<String>();


for(Lead l : leads){
if(l.leadSource == 'email)
compNames.add(l.company);
}

Clone => take the duplicate of one list to another

List<Lead> leads = new List<Lead>{l1, l2, l3};


System.debug('leads :: ' + leads);

List<Lead> newLeads = leads.clone();


System.debug('newLeads' + newLeads);

List<Lead> leads = [Select Name from Lead];


System.debug('leads :: ' + leads);

List<Lead> newLeads = leads.clone();


System.debug('newLeads' + newLeads);

EXERCISE – LIST OF sObject Type


1. Declare the list of opportunities and store 3 opportunity records as below
Name Amount StageName CloseDate
Opty1 10000 Closed Won 2019-10-30
Opty2 2000 Prospecting 2019-10-25
Opty3 0 Closed Lost today

i. Get the 1st opportunity from the oppList and store into another variable
ii. Get the 3rd element from the oppList
iii. Display opportunity record in the log one by one from the oppList
iv. Display each opportunity name in the log
v. Display each opportunity amount in the log
vi. Sum up all the opportunity amounts
vii. Get all the opportunity names from the oppList and store into another collection
viii. Store the opportunity names into another collection only if amount is greater than 0
ix. Sum up all the opportunities amount if close date is today and display the total amount in the log.

2. Create 3 case records as below and store (initialize) into list of case
Subject Status Origin
Case1 Open Web
Case2 Open Email
Case3 Escalated Phone

3. Create 3 lead records as below and store into list of lead


lastName Company LeadSource AnnualRevenue
aaa comp1 email 10000
bbb comp2 phone 15000
ccc comp3 email 5000
i. Display each lead record one by one in the log
ii. Display the lead lastName one by one in the log
iii. Sum up annual revenue of all the lead records
iv. Get all the company names into another collection if lead source is email.

10. SET
 Collection of UNIQUE elements

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 42


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

 It will not accept duplicates


 Order of insertion is not maintained

Syntax:
Set<dataType> setName;

Example:
Set<String> compNames;
Set<empNo> empNos;
Set<Integer> accountNos;

Set<ID> accIds ;
Set<Account> accounts;

Allocating memory:
Set<String> compNames = new Set<String>();

Methods of Set
1. Add element: add(element)

compNames.add('TCS');
compNames.add('CTS');
compNames.add('Infosys');
compNames.add('TCS');
compNames.add('CTS');
compNames.add('FIS');

System.debug(compNames);

output: {CTS, FIS, Infosys, TCS}


//set will ignore the duplicate elements

2. Remove the element - remove(element)


i. remove the company TCS from the list compNames
compNames.remove('TCS');

3. remove all the list elements : clear()


compNames.clear()

4. To check if list is empty : isEmpty()


Boolean flag = compNames.isEmpty();

5. to copy one list to another set: addAll(list/set);


List<Integer> numbers1 = new List<Integer>{10,30,30,40,50,60};
Set<Integer> numbers2 = new Set<Integer>{11,22,33,66,99};

System.Debug('numbers 1 :: ' + numbers1);


System.debug('numbers 2 :: ' + numbers2);

numbers2.addAll(numbers1);
System.debug('after copied :: ' + numbers2);

6. to check if number 10 exists: contains(element)


Boolean flag = numbers.contains(10);

7. To compare the list with set : containsAll(list/set)

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 43


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

List<Integer> numbers1 = new List<Integer>{10,30,30,40,50,60};


Set<Integer> numbers2 = new Set<Integer>{10,20,30,40,50};

Boolean flag = numbers2.containsAll(numbers1);


System.debug(flag);

Exercise - SET
1. Write the syntax for a Set declaration.
2. What is set? When do we mostly use the Set?
3. Declare a set of Integer ‘Ages’ and add values 60, 70, 30, 30, 50, 60 using add method
4. Declare a set of String ‘Names’ and add values such as ‘Ranjith’,’Krishnan’,’Uma’,’David’,’Ram’
5. Declare a set of String ‘CompanyNames’ and initialize with 5 different company names such as
‘TCS’,’CTS’,Test,’Infosys’,’HCL’
i. Display the company name one by one in the log
ii. Remove the company name ‘Test’ from the set and display the final set in the log
iii. Check if company name ‘HCL’ is there in the set
iv. Add a company ‘Virtusa’ into the set CompanyNames
v. Declare a set of newCompanies with values ‘Wintel’,’Samson’,’Matrix’
vi. Add all the company names from the set newCompanies into the set CompanyNames

11. MAP
 It is a collection of Key Value pair.
 Key is unique and Value can be duplicated.
 It is of primitive or reference types.

Methods:
put(key, value) : To add element into map
get(key) : To get value based on key
containsKey(key) : To check if particular key exists in the map
values() : To get all the values of the map
keySet() : To get all the keys from the map

Input Data
Student Table
Use Case 1
Name Phone Email Fee
Ravi 1234 ravi@gmail.com 1000
Reddy 6888 reddy@gmail.com 2000
Sam 7979 sam@gmail.com 3000
Ranjith 8080 ranjith@gmail.com 2000

1. Create a map of name as key and email as value.


Map<String, String> studMap1 = new Map<String, String>();
studMap1.put('Ravi','ravi@gmail.com');
studMap1.put('Reddy','reddy@gmail.com');
studMap1.put('Sam','sam@gmail.com');
studMap1.put('Ranjith','ranjith@gmail.com');

2. Create a map of name as key and phone no as value.


Format 1: (dynamic)

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 44


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Map<String, String> studMap2 = new Map<String, String>();


studMap2.put('Ravi','1234');
studMap2.put('Reddy','6888');
studMap2.put('Sam','7979');
studMap2.put('Ranjith','8080')

3. Create a map of name as key and fee as value


Format 2: (Static initialization)
Map<String, Decimal> studMap3 = new Map<String, Decimal>{'Ravi'=>1000, 'Reddy'=>2000,
'Sam'=>3000,'Ranjith'=>1000};
System.debug(studMap3);

i. get all the student name from the map studMap3 and store into another collection (set of string)
Set<String> studNames = studMap3.keySet();

ii. get all the fees from studMap3 and store into another set of decimal.
List<Decimal> studFees = studMap3.values();

iii. Sum up all the fees from studMap


for( variable : array/list/set){

}
List<Decmial> fees = studMap3.values();
Decimal totalFee = 0.0;
for(Decimal f: fees){
totalFee = totalFee + f;
}

iv. Get studnames into another set of string whose fee is greater > 1000
a. key => student name
b. value => fee => get student name only if fee > 1000

Set<String> names = new Set<String>();


for(String s : studMap3.keySet()){
if( studMap3.get(s) > 1000 ) // using get(key) we can get the value
names.add(s);
}
System.debug(names);

v. Get studNames only if fee > 2000


Use Case 2
Input Data
Employee Table
name salary city exp
aaa 4000 hyd 4
bbb 1000 chn 2
ccc 2000 bng 1

i. Declare the map of employee name as key and salary as value with initializing the above

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 45


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Map<String, Decimal> empMap = new Map<String, Decimal>{'aaa'=>4000, 'bbb'=>1000, ccc=>2000};

ii. get all the salaries from empMap and store into another list of decimal
List<Decimal> salaries = empMap.values();
Decimal totalsal = 0.0;
for(Decimal s : salaries){
totalSal = s + totalSal;
}
System.debug(totalSal);

iii. get all the empNames into another collection (set of string)
Set<String> names = empMap.keySet();

iv. get emp names only if salary > 1000


Set<String> names = empMap.keySet();
Set<String> newNames = new Set<String>();

for(String s : names){
if( empMap.get(s) > 1000 )
newNames.add(s);
}

Other Format
//Set<String> names = empMap.keySet();
Set<String> newNames = new Set<String>();

for(String s : empMap.keySet() ){
if( empMap.get(s) > 1000 )
newNames.add(s);
}

Map of sObject type:


Declare a map of Account name as key and account record as value

key: String
value: account

Map<String, Account> accMap = new Map<String, Account>();

1. Declare a map of Account Name as key and Industry as value


key: String
value: String
Map<String, String> accMap1 = new Map<String, String>();

2. Declare a map of case subject as key and case record as value


key: string
value: case
Map<String, Case> caseMap = new Map<String, Case>();

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 46


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

3. Declare a map of student name as key and student__C record as value


key: string
value: student__C
Map<String, Student__c> studMap = new Map<String, Student__c>();

4. Declare a map with account name as key and account record as value
Map<String, Account> accMap = new Map<String, Account>();
i. insert 3 elements into accMap

Account a1 = new Account(Name='test acc1', Industry='Energy', Rating= 'hot');


Account a2 = new Account(Name='test acc2', Industry='Apparel', Rating='cold');
Account a3 = new Account(Name='test acc3', Industry='Energy', Rating='warm');

accMap.put(a1.Name, a1);
accMap.put(a2.Name, a2);
accMap.put(a3.Name, a3);

System.debug(accMap);

( key1=value1,key2=value2,key3=value3);

Output
Key = Value
(String) (Account)
{test acc1=Account:{Name=test acc1, Industry=Energy, Rating=hot},
test acc2=Account:{Name=test acc2, Industry=Apparel, Rating=cold},
test acc3=Account:{Name=test acc3, Industry=Energy, Rating=warm}}

i. get all the account records from the accMap


List<Account> accList = accMap.values();

ii. get all account names from the accMap


Set<String> accNames = accMap.keySet();

iii. get all the industry values from accMap and store into another collection (list of String)
List<Account> accList = accMap.values();
List<String> industries = new List<String>();
for(Account a : accList){
industries.add(a.Industry);
}

0 1 2
------------------------------------------
energy | apparel | energy |
-----------------------------------------

iv. get all the ratings from the map accList and store into another list of string
List<String> ratings = new List<String>();
for(Account a : accMap.values()){

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 47


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

ratings.add(a.rating);
}

v. get the unique industry values from the map accList;


Set<String> uniqueIndustries = new Set<String>();
for(Account a : accMap.values()){
uniqueIndustries.add(a.Industry);
}

5. Create 3 opportunity records with below values


Name Amount CloseDate StageName
oppty1 1000 2019-30-09 Prospecting
oppty2 0 2019-24-09 CLosed Lost
oppty3 4000 today Closed Won
oppty4 3000 today Closed Won

Opportunity op1 = new Opportunity();


op1.Name ='oppty1';
op1.Amount=1000;
op1.CloseDate = Date.newInstance(2019,09,30) ;
op1.StageName = 'Prospecting';

Opportunity op2 = new Opportunity(Name='oppty2', Amount=0,


closeDate=Date.newInstance(2019,09,24),
StageName='Closed Lost');
Opportunity op3 = new Opportunity(Name='oppty3', Amount=4000, closeDate=Syste.today(),
StageName='Closed Won') ;
Opportunity op4 = new Opportunity(Name='oppty4', Amount=3000, closeDate=Syste.today(),
StageName='Closed Won') ;

i. Create a map of opportunity name as key and opportunity record as value and intialize with elements.
Map<String , Opportunity> oppMap = new Map<String, Opportunity>{op1.Name => op1, op2.Name => op2,
op3.Name => op3, op4.Name => op4};
Add the below one into oppMap
Opportunity opty5 = new Opportunity(Name='test', closeDate='Prospecting');

oppMap.put(opty4.Name, opty5);

From oppMap
i. Create a map of opportunity name as key and closeDate as value
Map<String, Date> oppMap1 = new Map<String, Date>();
List<Opportunity> opps = oppMap.values();
for(Opportunity o: opps){
oppMap1.put(o.Name, o.closeDate);
}

ii. Create map of opportunity of stageName as key and amount as value


Map<String, Decimal> oppMap2 = new Map<String, Decimal>();
List<Opportunity> opps = oppMap.values();

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 48


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

for(Opportunity o: opps){
oppMap2.put(o.stageName, o.Amount);
}

11.1 MULTI-DIMENSIONAL LIST/SET/MAP

List<String> names = new List<String>{'aaa','bbb','ccc',''ddd'};


0 1 2 3
-----------------------------------
aaa | bbb | ccc | ddd |
-----------------------------------

List<String> newNames = new List<String>{'ttt','yyy','zzz'};


0 1 2
-----------------------
ttt | yyy | zzz |
-----------------------
String name = newNames.get(0);

List< List<String> > nameList = new List<List<String>>();


dataType => list of String

namesList.add(names);
namesList.add(newNames);
0 1
-----------------------------------------
List<String > | List<String>
(names) | (newNames)
----------------------------- -----------
List<String> names1 = nameList .get(0);

11.2 EXERCISE – MAP


Input Data
Student Table
Use Case 1
Name Phone Email Fee
Ravi 1234 ravi@gmail.com 1000
Reddy 6888 reddy@gmail.com 2000
Sam 7979 sam@gmail.com 3000
Ranjith 8080 ranjith@gmail.com 2000

1. Create a map of name as key and email as value.


2. Create a map of name as key and phone no as value.
3. Create a map of name as key and fee as value
i. get all the student name from the map studMap3 and store into another collection (set
of string)

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 49


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

ii. get all the fees from studMap3 and store into another set of decimal.
iii. Sum up all the fees from studMap
iv. Get studnames into another set of string whose fee is greater > 1000
v. Get studNames only if fee > 2000

11.3 Use Case 2


Input Data
Employee Table
name salary city exp
aaa 4000 hyd 4
bbb 1000 chn 2
ccc 2000 bng 1

i. Declare the map of employee name as key and salary as value with initializing the above
ii. get all the salaries from empMap and store into another list of decimal
iii. get all the empNames into another collection (set of string)
iv. get emp names only if salary > 1000

11.4 Map of sObject type:


Declare a map of Account name as key and account record as value
key: String
value: account

Map<String, Account> accMap = new Map<String, Account>();


6. Declare a map of Account Name as key and Industry as value
7. Declare a map of case subject as key and case record as value
8. Declare a map of student name as key and student__C record as value
9. Declare a map with account name as key and account record as value
Map<String, Account> accMap = new Map<String, Account>();
i. insert 3 elements into accMap
ii. get all the account records from the accMap
iii. get all account names from the accMap
iv. get all the industry values from accMap and store into another collection (list of String)
v. get all the ratings from the map accList and store into another list of string
vi. get the unique industry values from the map accList;

10. Create 3 opportunity records with below values


Name Amount CloseDate StageName
oppty1 1000 2019-30-09 Prospecting
oppty2 0 2019-24-09 CLosed Lost
oppty3 4000 today Closed Won
oppty4 3000 today Closed Won

iii. Create a map of opportunity name as key and opportunity record as value and intialize with elements.
iv. Create map of opportunity of stageName as key and amount as value

LIST – SET Scenarios

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 50


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Input Data
Name: Order Table
OrderID CustomerName Price
OR001 Ranjith 100
OR002 Sam 200
OR003 Savitha 100
OR004 David 150
OR005 Sam 300

1. Create list of customer name.


Format 1: Static initialization
List<String> customers = new List<String>{'Ranjith', 'Sam', 'Savitha', 'David', 'Sam'};

Format 2: using add(element)


List<String> customers = new List<String>();

customers.add('Ranjith');

*******************************
2. Create a list of orderIds and add all the order ids into the list
using format1:
using format2:

3. From the 'Customers' list.


************************
List<String> customers = new List<String>{'Ranjith', 'Sam', 'Savitha', 'David', 'Sam'};

i. display the customer name one by one in the log


using for Each Loop
for(variable : array/list/set){}

for(String c: customers){
System.debug(c);
}

ii. get only the unique customer names into another set of string.
method 1:
Set<String> uniqueNames = new Set<String>();
for(String c: customers){
uniqueNames.add(c);
}

method 2: (Syntax: Set<dataType> setName = new Set<dataType>(list/set))


Set<String> uniqueNames = new Set<String>(customers);

iii. get the customer name in index 2 and store into another string variable
using get(index):
String cust1 = customers.get(2);

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 51


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

iv. using If condition, check if the customer 'David' is there in the list
display in the log as 'customer is present' if david is found in the list else
display in the log as 'customer not found'.

Using contains(element): returns true or false


if(customers.contains('David'))
System.debug('customer is present');
else
System.debug('customer not found');

v. insert a new customer 'reddy' into the list as the last element
customers.add('reddy');
System.debug(customers);

vi. insert a new customer 'ramesh' into the list in index 3. Display the final list 'Customers'
into the log.
using add(index, element);
customers.add(3, 'ramesh');
System.debug(customers);

vii. replace the customer name 'Sam' in the list with 'Sam Sundar'.
Display the final list 'customers' into log.
using set(index, element)
using indexOf(element)
a. Integer i = customers.indexOf('Sam');
b. customers.set(i,'Sam Sundar');
System.debug(customers);

viii. Check if the customer 'Sam Sundar' is available in the list. If found, then store the boolean value into
another variable 'customerFound' of boolean type.
using contains(element)

Boolean customerFound = customers.contains('Sam Sundar');


System.debug('is customer found (true / false )? ' customerFound);

ix. Create another list of string named 'oldCustomers' with values 'bob','shravya','kiran'
Copy all the customer names from the list 'oldCustomers' to the list 'Customers'.
Display the final list 'Customers' into the log.
using addAll(list / set);

List<String> oldCustomers = new List<String>{'bob','shravya','kiran'};


customers.addAll(oldCustomers);
System.debug('after copied old list to customers : ' + customers);

x. Sort the list customers and display the final list into the log.
customers.sort();
System.debug('after sorted the names : ' + customers) ;

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 52


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

xi. get the total number of unique customer names in the list 'customers'.
a. Set<String> uniqNames = new Set<String>(customers);
b. Integer totalCustomer = uniqNames.size();

12. How to refer the collection in apex?


List => collections

VF Page: standardcontroller => is for one record


standardController recordsetVar => is for collections of records

Collections of records: Which VF components can be used to display table of data?


1. apex:pageBlockTable
2. dataTable
3. dataList
4. repeat

The above components can also be used to iterate the list from apex as below.

Apex class
public List<String> customers {get; set;}

public void getCustomer(){


customers = new List<String>{'Ranjith', 'Sam', 'Savitha', 'David', 'Sam'};
}

VF Page:
<apex:pageBlock>
<apex:pageBlockTable value="{!customers}" var="c">
{!c}
</apex:pageBlockTable>
</apex:pageBlock>

Example 1
Apex:
public class ListExample1 {
public List<String> customers {get; set;}

// the constructor method will be the first method runs when the VF page is loaded
public ListExample1(){
customers = new List<String>{'Ranjith', 'Sam', 'Savitha', 'David', 'Sam'};
}
}

VF Page:
<apex:page controller="ListExample1">
<apex:pageBlock >
<apex:pageBlockTable value="{!customers}" var="c">
<apex:column value="{!c}" headerValue="Customer Name"/>
</apex:pageBlockTable>

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 53


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

</apex:pageBlock>
</apex:page>

Example: Write a class with list of cities as variable


i. using constructor intialize the list with values 'hyd','chn','pune','dlh','noida'
ii. Display the city name in the VF page using data list component. (pageBlock 1)
iii. Also display the city name in the page using dataTable component. (pageBlock 2)
- apply the borders, cellpadding to the datatable
Apex:
public class listExample2 {
public List<String> cities {get; set;}

public listExample2(){
cities = new List<String>{'hyd','chn','pune','dlh','noida'};
}

VF Page:
<apex:page controller="listExample2">
<apex:pageBlock title="using dataList">
<apex:dataList value="{!cities}" var="c">
<apex:outputText >{!c}</apex:outputText>
</apex:dataList>
</apex:pageBlock>

<apex:pageBlock title="using dataTable">


<apex:dataTable value="{!cities}" var="c" border="1" cellpadding="2">
<apex:column value="{!c}"/>
</apex:dataTable>
</apex:pageBlock>
</apex:page>

12.1 EXERCISE – LIST IN VF AND APEX


Input Data Name: Order Table
OrderID CustomerName Price
OR001 Ranjith 100
OR002 Sam 200
OR003 Savitha 100
OR004 David 150
OR005 Sam 300

1. Create list of customer name.


2. Create a list of orderIds and add all the order ids into the list
3. from the 'Customers' list.
List<String> customers = new List<String>{'Ranjith', 'Sam', 'Savitha', 'David', 'Sam'};

i. display the customer name one by one in the log

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 54


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

ii. get only the unique customer names into another set of string.
iii. get the customer name in index 2 and store into another string variable
iv. using If condition, check if the customer 'David' is there in the list
v. insert a new customer 'reddy' into the list as the last element
vi. insert a new customer 'ramesh' into the list in index 3. Display the final list 'Customers'
into the log.
vii. replace the customer name 'Sam' in the list with 'Sam Sundar'.
viii. Check if the customer 'Sam Sundar' is available in the list. If found, then store the boolean value into another
variable 'customerFound' of boolean type.
ix. Create another list of string named 'oldCustomers' with values 'bob','shravya','kiran'
x. Sort the list customers and display the final list into the log.
xi. get the total number of unique customer names in the list 'customers'.

Exercise 1: Write a class with list of cities as variable


using constructor intialize the list with values 'hyd','chn','pune','dlh','noida'
Display the city name in the VF page using data list component. (pageBlock 1)
Also display the city name in the page using dataTable component. (pageBlock 2)
- apply the borders, cellpadding to the datatable

Exercise 2: Write a class with variable 'bankNames' of list<String>


using constructor intialize the list with values 'hdfc','hsbc','sbi','citi','idbi'.
Write a VF page to display the banknames one by one using dataTable component

Example 1: Display the list of accounts in VF page


Create 5 account records and add into list.
Write a Class: getAccountList
variable: List<Account> accs

Constructor
Account a1 = new Account(name='abc', industry='energy');
Account a2 = new Account(name='bcd', industry='apparel');
Account a3 = new Account(name='dec', industry='education');
Account a4
Account a5
initialize the accs

VF page:
Display the table from the list accs (dataTable)
Name Industry

Class:
public class getAccountList {
public List<Account> accs {get; set;}

public getAccountList(){
Account a1 = new Account(name='abc', industry='energy');
Account a2 = new Account(name='bcd', industry='apparel');
Account a3 = new Account(name='dec', industry='education');
Account a4 = new Account(name='rrr', industry='technology');
Account a5 = new Account(name='yyy', industry='apparel');

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 55


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

accs = new List<Account>{a1, a2, a3, a4, a5};


}
}

Page:
<apex:page controller="getAccountList">
<apex:pageBlock title="Account List Demo">
<apex:dataTable value="{!accs}" var="a" border="1">
<apex:column headerValue="Name" value="{!a.Name}"/>
<apex:column headerValue="Industry" value="{!a.Industry}"/>
</apex:dataTable>
</apex:pageBlock>
</apex:page>

12.2 LIST WITH SIMPLE SOQL


Simple SOQL
Simple Syntax
Select field1, field2, field3 From ObjectName;

Example: To get all accountname, phone, industry from account object

Select name, phone, industry From Account

Integer i = 4;
List<Account> accs = [Select name, phone, industry, rating From Account] // in apex

Note: by default SOQL query will return list of sObject records


Output:
(Account:{Name=Ranjith, Id=0012v00002UtnVaAAJ},
Account:{Name=tet, Id=0012v00002UtnYoAAJ},
Account:{Name=Ranjith, Id=0012v00002UtnRYAAZ},
Account:{Name=Ranjith, Id=0012v00002UtnWYAAZ},
Account:{Name=Ranjith, Id=0012v00002UtnWdAAJ},
Account:{Name=test 2, Id=0012v00002UtnbTAAR},
Account:{Name=test, Id=0012v00002UtnaLAAR},
Account:{Name=test, Id=0012v00002UtnbnAAB},
Account:{Name=NIIT, Industry=sfdcmeet@gmail.com, Id=0012v00002UsikzAAB},
Account:{Name=CTS, Industry=Technology, Id=0012v00002Usi

Store into a collection variable.


1. Write a query to fetch firstname, lastName, email, phone from Contact.
variable = [soql];
List<Contact> conList = [Select firstName, lastName, email, Phone from Contact];

2. Fetch subject, status, reason, priority from case object


List<Case> cases = [Select subject, status, reason, priority From Case];

3. Fetch name, amount, stageName. closeDate from Opportunity


List<Opportunity> oppList = [Select Name, Amount, StageName, closeDate
From Opportunity];

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 56


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

List<Account> accs = [Select name, phone, industry, rating From Account];


0 1 2
--------------------------------------------------
| account1 | account2 | account3 |

To get first element from accs


Account a1 = accs.get(0);
a1.Name
a1.phone
a1.industry
a1.rating
a2.annualRevenue // can not be referred

List<Opportunity> oppList = [Select Name, Amount, StageName, closeDate From Opportunity];

Output:
// Index: 0
Opportunity:{Name=test Opty, Amount=4000.00, StageName=Prospecting, CloseDate=2019-10-09 00:00:00,
Id=0062v00001GDbbYAAT},
// Index: 0
Opportunity:{Name=GenePoint SLA, Amount=30000.00, StageName=Closed Won, CloseDate=2019-08-28 00:00:00,
Id=0062v00001G9RsuAAF},

i. get the 2nd opportunity record from oppList and store into a variable (Opportunity o1)
Opportunity op1 = oppList.get(1);

ii. display the opportunity record one by one from the oppList in the log.
for(Opportunity o :oppList){
System.debug(o);
}

iii. get only the opportunity names from the oppList and store into list of string
List<String> oppNames = new List<String>);
for(Opportunity o :oppList){
oppNames.add(o.Name);
}
12.3 EXERCISE – LIST – VF APEX
Write a class with data member list<String> customers , Integer ind, String name
i. Include constructor to initialize the customers with values
'sam','surya','kapil','ranjith','kavya'
ii. Include a method getCustomer() with below logic
i. based on the index, get the customer name from the list customers
and store into another variable.
public void getCustomer(){
String custName = customers.get(ind);
}
iii. Include a method insertCustomer() with below logic
i. add the customer name into existing list 'customers'

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 57


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

VF page:
i. Get the index value : apex:inputText value="{!ind}"
ii. Get the customer name : apex:inputText value="{!name}"
Include two commandButtons
i. apex:commandButton action="{!getCustomer}"
ii. apex:commandButon action="{!insertCustomer}"
iii. Add pageBlock to display the customer details

12.4 EXERCISE – LIST - SOQL


Ex1: i. Write a class ‘AccountCont’ with constructor
ii. Inside Constructor, create 5 account records and add into list.
iii. Display the list of accounts in VF page
Ex2: Fetch all accountname, phone, industry from account object and store into a list
Ex3: Write a query to fetch firstname, lastName, email, phone from Contact.
Ex4: Fetch subject, status, reason, priority from case object
Ex5: Fetch name, amount, stageName. closeDate from Opportunity
i. get the 2nd opportunity record from oppList and store into a variable (Opportunity o1)
ii. display the opportunity record one by one from the oppList in the log.
iii. get only the opportunity names from the oppList and store into list of string

Ex6: Fetch Name, Rating, Annual Revenue, Industry from Account object and store into a list.
i. Get total number of records fetched
ii. Get 1st record from accsList
iii. Get all the account names into another collection
iv. Get AnnualRevenues of accounts into another collection only if the industry is 'Energy'

Ex7: Fetch name, stageName, amount, closedate of opportunity into a list


i. get all the names of the opportunity into another collection
ii. get all the unique stageNames into another collection
iii. sum up the amounts of all opportunities if the stage is closed won.

Ex8: Fetch name, email, phone from contact object into a list
i. Get all contact names into another collection
ii. Get unique emails of all the contacts only if email is not empty

Ex9: i. Fetch phone nos of all the contacts into another list of string - 'contactPhones'
ii. Fetch phone nos of all the accounts into another list of string - 'accountPhones'
iii. Store the above list 'contactPhones' and 'accountPhones' into new list of string.

Ex1
List<Account> accsList = [Select Name, Rating, AnnualRevenue, industry from Account];
//to get size
integer count = accsList.size();

// to get 1st record from accsList


Account a = accsList.get(0);
String name = a.Name;

//to get all the account names into another collection

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 58


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

List<String> names = new List<String>();


for(Account a : accsList){
names.add(a.Name);
}

// get AnnualRevenue into another collection only if industry = 'Energy'


Ex2: Fetch name, stageName, amount, closedate of opportunity into a list
List<Opportunity> oppList = [Select name, stageName, amount, closedate From Opportunity];
i. get all the names of the opportunity into another collection
List<String> oppNames = new List<String>();
for(Opportunity op: oppList){
oppNames.add( op.Name );
}
ii. get all the unique stageNames into another collection
Set<String> uniqueStages = new Set<String>();
for(Opportunity op:oppList){
uniqueStages.add(op.stageName);
}

iii. sum up the amounts of all opportunities if the stage is closed won.
Decimal totalValues = 0.0;
for(Opportunity op: oppList){
if(op.stageName == 'Closed Won')
totalValues = totalValues + op.Amount;
}

Ex3: Fetch name, email, phone from contact object into a list
List<Contact> conList = [Select name, email, phone From Contact];
i. Get all contact names into another collection
List<String> contactNames = new List<String>();
for(Contact c:conList){
contactNames.add(c.Name);
}

ii. Get unique emails of all the contacts only if email is not empty
Set<String> conEmails = new Set<String>();
for(Contact c : conList){
if(c.Email != null or !String.isEmpty(c.Email)) //String is class ; isEmpty() static
conEmails.add(c.Email);
}

Ex4: i. Fetch phone nos of all the contacts into another list of string - 'contactPhones'
if phone is not null
a. use SOQL to get all the contacts (phone)
List<Contact> cons = [Select Phone From Contact]; // id, phone

b. loop the list and get the phone numbers into another collection 'contactPhones'
List<String> contactPhones = new List<String>();
for(Contact c : cons){

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 59


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

if(c.Phone != null)
contactPhones.add(c.Phone);
}

ii. Fetch phone nos of all the accounts into another list of string - 'accountPhones'
if phone is not null
a. use SOQL to get all the accounts (phone)
List<Account> accs = [Select Phone from Account];

b. loop the list and get the phone numbers into another collection 'accountPhones'
List<String> accountPhones = new List<String>();
for(Account a : accs){
if(a.Phone != null){
accountPhones.add(a.Phone);
}
}

iii. Store the above list 'contactPhones' and 'accountPhones' into new list of string.
addAll(list)
List<String> allPhones = new List<String>();
allPhones.addAll(contactPhones);
allPhones.addAll(accountPhones) ;

VF Page:
Variable pagebLocktable
List<Account> accs value="{!accs}"
List<String> empNames value="{!empNames}"
List<Contact>
List<Student__C>

13. WHAT IS WRAPPER CLASS ?


Class contains only data members

Custom dataType How to refer in VF page


Account & Boolean value={!WrapperClass}

Example:
public class AccountWrapper {
public Account a;
public Boolean flag;
}

Declaring the variable of wrapper type:


AccountWrapper accWrap;

Initializing
accWrap = new AccountWrapper();

Create one instance of wrapper class type

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 60


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Account a1 = new Account(name ='test');


accWrap.a = a1;
accWrap.flag = true;

Create list of wrapper class type


List<AccountWrapper> accWrapList;

accWrapList = new List<AccountWrapper> ();


accWrapList.add(accWrap );

Variable in Apex pageBlockTable in VF Page


List<AccountWrapper> accWrapList value="{!accWrapList }

13.1 VF and APEX Scenario for Wrapper Class


public class AccountWrapper {
public Account a {get; set;}
public Boolean flag {get; set;}
}

List<AccountWrapper> accWrapList = new List<AccountWrapper>();

List<Account> accs = [Select Name, phone, Rating, Industry From Account];

One Element for accWrapList ;


AccountWrapper aw1 = new AccountWrapper();
aw1.a = accs.get(0);
aw1.flag =false;
accWrapList.add(aw1);

for(Account a1 : accs){
AccountWrapper aw1 = new AccountWrapper();
aw1.a = a1;
aw1.flag =false;
accWrapList.add(aw1);
}

Example:
1. Write a wrapper class 'ContactWrapper' with data members
Contact c {get; set;}
Boolean flag {get; set;}

public class ContactWrapper { // user defined data type


public Contact c {get; set;}
public Boolean flag {get; set;}
}

2. Write a class 'ContactCont' with below data member


List<ContactWrapper> conWrapList {get; set;}

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 61


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Constructor:
i. Fetch lastName, firstname, phone, email from contact and store into a list 'conList'
ii. Insert element into conWrapList by taking contact records from conList.

public class ContactCont {


public List<ContactWrapper> conWrapList {get; set;}
public List<Contact> selectedContacts {get; set;}

public ContactCont(){
//memory allocation
conWrapList = new List<ContactWrapper>();
selectedContacts = new List<Contact>();

//fetch contact records


List<Contact> conList = [Select lastName, firstname, phone, email From Contact];

//create elements to insert into conWrapList


for(Contact c :conList ){
ContactWrapper cw1 = new ContactWrapper();
cw1.c = c;
cw1.flag = false;
conWrapList.add(cw1);
}
}

public void submit(){


for(ContactWrapper cw:conWrapList){
if(cw.flag)//
selectedContacts.add(cw.c);
cw.flag = false;
}
}
}

3. Write a VF page to display the conWrapList using dataTable (use the attributes cellpadding, rules, width,
frame etc.,).
Display the columns - firstname, lastName, email, phone

4. Display the selected contact records into another block by click on submit button.
<apex:page controller="ContactCont" sidebar="false">
<apex:form >
<apex:pageBlock title="Contacts">
<apex:commandButton value="submit" action="{!submit}" reRender="sel"/>
<apex:dataTable value="{!conWrapList}" var="cw" frame="border" rules="rows" cellpadding="3">
<apex:column headerValue="Select" >
<apex:inputCheckbox value="{!cw.flag}"/>
</apex:column>
<apex:column value="{!cw.c.firstName}" headerValue="first name"/>
<apex:column value="{!cw.c.lastName}" headerValue="last name"/>

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 62


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

<apex:column value="{!cw.c.phone}" headerValue="phone"/>


<apex:column value="{!cw.c.email}" headerValue="email"/>
</apex:dataTable>
</apex:pageBlock>

<apex:pageBlock id="sel">
<apex:dataTable value="{!selectedContacts}" var="c" cellpadding="3" frame="border" rules="rows">
<apex:column value="{!c.firstname}" headerValue="first Name"/>
<apex:column value="{!c.lastName}" headerValue="last Name"/>
<apex:column value="{!c.email}" headerValue="email"/>
<apex:column value="{!c.phone}" headerValue="phone"/>
</apex:dataTable>
</apex:pageBlock>
</apex:form>
</apex:page>

Example:
i. Write a wrapper class OpportunityWrapper with datamembers
Opportunity op;
Boolean flag;

public class OpportunityWrapper {


public Opportunity opp {get; set;}
public Boolean flag {get; set;}
}
ii. Write a class 'OppController' with below data members
a. List<OpportunityWrapper> oppList;
b. Within Constructor
a. get all opportunities with name, amount, stage, closedDate
b. populate the OpportunityWrapper with opportunity records

public class OppController {


public List<OpportunityWrapper> oppWrapList {get; set;}
public List<Opportunity> closedOpps {get; set;}

public OppController(){
List<Opportunity> oppList = [Select name, amount, stageName, closeDate From Opportunity];
oppWrapList = new List<OpportunityWrapper>();
closedOpps = new List<Opportunity>();
for(Opportunity o : oppList){
OpportunityWrapper ow = new OpportunityWrapper();
ow.opp = o;
ow.flag = false;
oppWrapList.add(ow);
}
}

public void closedOpps(){


for(OpportunityWrapper ow:oppWrapList){

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 63


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

if(ow.flag && (ow.opp.stageName == 'Closed Won' || ow.opp.stageName == 'Closed Lost'))


closedOpps.add(ow.opp);
}
}
}

iii. Write a Vf page to display the OpportunityWrapper fields as below


--------------------------------------------------------------------------
Select | Name | Amount | CloseDate | StageName
--------------------------------------------------------------------------
a. Include buttons such as open opps and closed opps
b. When user clicks on 'Open Opps', display only the opportnities in another block those are selected and whose
stage is not closed (StageName != 'Closed Lost' AND 'Closed Won')
c.. When user clicks on 'closed Opps', display only the opporunities in another block those are selected and whose
stage is closed. (StageName == 'Closed Lost' OR StageName=='Closed Won')

<apex:page controller="OppController">
<apex:form >
<apex:pageBlock >
<apex:commandButton value="Open Opps"/> &nbsp;&nbsp;
<apex:commandButton value="Closed Opps" action="{!closedOpps}" reRender="res"/>
<apex:pageBlockTable value="{!oppWrapList}" var="ow">
<apex:column >
<apex:inputCheckbox value="{!ow.flag}"/>
</apex:column>
<apex:column value="{!ow.opp.Name}"/>
<apex:column value="{!ow.opp.Amount}"/>
<apex:column value="{!ow.opp.StageName}"/>
<apex:column value="{!ow.opp.CloseDate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock id="res">
<apex:pageBlockTable value="{!closedOpps}" var="op">
<apex:column value="{!op.Name}"/>
<apex:column value="{!op.Amount}"/>
<apex:column value="{!op.StageName}"/>
<apex:column value="{!op.CloseDate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
13.2 EXERCISE – WRAPPER CLASS - LIST
1. Write a wrapper class 'ContactWrapper' with data members
Contact c {get; set;}
Boolean flag {get; set;}
2. Write a class 'ContactCont' with below data member
3. Write a VF page to display the conWrapList using dataTable (use the attributes cellpadding, rules, width,
frame etc.,).
Display the column

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 64


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

select, firstname, lastName, email, phone


4. Display the selected contact records into another block by click on submit button.

5. Write a class 'OppController' with below data members


a. List<OpportunityWrapper> oppList;
b. Within Constructor
a. get all opportunities with name, amount, stage, closedDate
b. populate the OpportunityWrapper with opportunity records

6. Write a Vf page to display the OpportunityWrapper fields as below


--------------------------------------------------------------------------
Select | Name | Amount | CloseDate | StageName
--------------------------------------------------------------------------
a. Include buttons such as open opps and closed opps
b. When user clicks on 'Open Opps', display only the opportnities in another block those are selected and whose
stage is not closed (StageName != 'Closed Lost' AND 'Closed Won')
c.. When user clicks on 'closed Opps', display only the opporunities in another block those are selected and
whose stage is closed. (StageName == 'Closed Lost' OR StageName=='Closed Won').

14. Use Cases:


14.1 Use Case 1: Adding data / removing data in list through page
Write class ListExample3
a. Within Constructor
Initialize the list of String with customer names 'ramu','siva','arun','reddy','kiran'

Write a VF page to display the above customers under a section ‘Existing Customers’
a. Include text box to get an index
b. Include a command button to search the customer name based on index entered above
c. If customer found, then display then the customer in a section below the text box

d. Include text box to get customer name


e. Include a command button to add new customer name to the existing list
f. Then render the total list of customers below section ‘Existing Customers’

g. Include text box to get index


h. Include a command button to remove new customer name based on the index entered
i. Then render the final list of customers in a section

Apex Class
public class ListExample3 {
public Integer ind {get; set;}
public String displayName {get; set;}
public String name {get; set;}
public List<String> customers {get; set;}
public Boolean flag {get; set;} //null

public ListExample3(){
customers = new List<String>{'ramu','siva','arun','reddy','kiran'};
}

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 65


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

public void getCustomer(){


//get the element from the list based on index: get(index)
displayName = customers.get(ind);
}

public void addCustomer(){


//add element into the existing list : add(index)
customers.add(name);
customers.sort();
}

//add method removeCust() to remove the customer name from the list based on index
public void removeCust(){
//remove an element from list based on index : remove(index)
flag = true;
customers.remove(ind);
}
//add method clearAllCust() to remove all the customer names from the list
public void clearAllCust(){
customers.clear();
}
}
VF Page
<apex:page controller="ListExample3" sidebar="false">
<apex:form >
<apex:pageBlock tabStyle="Lead">
Enter Index: &nbsp;<apex:inputText value="{!ind}"/>
<apex:commandButton value="get Customer Name" action="{!getCustomer}" reRender="res1"/>

<apex:outputPanel id="res1">
<apex:pageBlockSection title="Customer Name" rendered="{!!ISNULL(displayName)}">
{!displayName}
</apex:pageBlockSection>
</apex:outputPanel> <br/>
Enter Name: &nbsp;<apex:inputText value="{!name}"/>
<apex:commandButton value="add New Customer" action="{!addCustomer}" reRender="res2"/>
<apex:pageBlockSection id="res2" title="Existing Customers">
<apex:dataList value="{!customers}" var="c" type="circle">
{!c}
</apex:dataList>
</apex:pageBlockSection>

Enter index to remove: &nbsp; <apex:inputText value="{!ind}"/>


<apex:commandButton value="remove element" action="{!removeCust}" reRender="res3"/>

<apex:outputPanel id="res3"> <!-- rendered="{!ISNULL(customers)}" -->


<apex:pageBlockSection title="After removed" rendered="{!flag}">

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 66


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

<apex:dataList value="{!customers}" var="c" type="circle">


{!c}
</apex:dataList>
</apex:pageBlockSection>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>

14.2 Use Case 2: Table with check box for record selection and display selected rows
Create a wrapper class ‘AccountWrapper’ with members

Account a
Boolean flag

ii. Create a class accClass


a. With members - Account a and List<AccountWrapper> accsWrap
b. Constructor to initialize the account and the List<AccountWrapper> accsWrap
c. add method to insert account record and add the inserted account into another list of
List<AccountWrapper> selectedWrap
d. del method to delete the record from the accsWrap

iii. Create a VF page with below section


Section 1
a. Get account name, industry, rating and annual revenue
b. Include a button save to call apex method to insert the new record into database.
c. Render the inserted record into another section (Section 2) one by one
Section 2
a. Show the inserted account in this section with check box in each row
b. When user selects one or more records then those records must be deleted.

Wrapper Class
public class AccountWrapper {
public Account a {get; set;}
public Boolean flag {get; set;}
}

Apex accClass
public class accClass {
public Account a {get; set;}
public List<AccountWrapper> accsWrap {get; set;} //removeAll()
public List<AccountWrapper> selectedWrap {get; set;}

public accClass(){
a = new Account();
accsWrap = new List<AccountWrapper>();
selectedWrap = new List<AccountWrapper>();
}
// insert the accound record and adding the record with flag into list of wrapperClass

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 67


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

public void save(){


insert a; //DML statement
AccountWrapper aw = new AccountWrapper(); // one element of accsWrap
aw.a = a;
aw.flag = false;
accsWrap.add(aw);
a = new Account(); //reset the inputFields
}

public void reset(){


a = new Account();
}

public void deleteAcc(){


selectedWrap = new List<AccountWrapper>();

//get only the selected record into selectedWrap


for(AccountWrapper aw :accsWrap){
if(!aw.flag){
selectedWrap.add(aw); //test2 & test3
}
}
//using removeALl method of set, more than one elements are removed
// accsWrap.removeAll(selectedWrap); //test 1 & test 4
accsWrap.clear();
accsWrap.addAll(selectedWrap);
}
}

VF Page
<apex:page controller="accClass" showHeader="false">
<apex:form >
<apex:pageBlock id="res">
<apex:pageBlockButtons location="top" >
<apex:commandButton value="save" action="{!save}" reRender="res"/>
<apex:commandButton value="reset" action="{!reset}" reRender="res"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:inputField value="{!a.Name}"/>
<apex:inputField value="{!a.Rating}"/>
<apex:inputField value="{!a.Industry}"/>
<apex:inputField value="{!a.AnnualRevenue}"/>
</apex:pageBlockSection>
<apex:actionRegion>
<apex:pageBlockSection title="Result" columns="1">
<apex:commandButton action="{!deleteAcc}" value="del" reRender="res"/>
<apex:pageBlockTable value="{!accsWrap}" var="aw">
<apex:column >

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 68


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

<apex:inputCheckbox value="{!aw.flag}"/>
</apex:column>
<apex:column value="{!aw.a.Name}"/>
<apex:column value="{!aw.a.Rating}"/>
<apex:column value="{!aw.a.industry}"/>
<apex:column value="{!aw.a.AnnualRevenue}"/>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:actionRegion>
</apex:pageBlock>
</apex:form>
</apex:page>

14.3 Use Case 3: Enable or Disable section and render table of data
Create a VF page to get employee details such as personal and experience details in two different sections.
i. Display only the personal details first like name, phone, email and isExperienced values
ii. Display the section ‘Experienced Details’ only when IsExperienced checkbox is enabled in previous
section.
iii. Include a button submit in the page so that when user clicks on it, the employee details entered must
be displayed in another block.

Output for test data:

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 69


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

Apex Class Code:


1. Create a wrapper class with details of employee such as name, phone, email, isExperienced, company.
public class EmployeeWrap {
public String name {get; set;}
public String email {get; set;}
public String phone {get; set;}
public String company {get; set;}
public Boolean isExperienced {get; set;}
}
Note: we use wrapper class here for a reusability of code as well as we are going to display the list of above
data as table in VF page.

2. Create a main class “EmployeeMainCls “


Variable declarations:
Name : Purpose
EmployeeWrap ew : To get input for the employee wrapper
List<EmployeeWrap>
empWrapList : To create list of employee records in apex so that we can
display in VF page after adding employee record
Boolean flag : To use in rendered attribute of section ‘employee details’

public class EmployeeMainCls {


public EmployeeWrap ew {get; set;}
public List<EmployeeWrap> empWrapList {get; set;}
public Boolean flag {get; set;}

public EmployeeMainCls(){
flag = false;
ew = new EmployeeWrap();
empWrapList = new List<EmployeeWrap>();
}
//Checking if the IsExperienced is true, then make the flag to true so that pageblockSection //‘Experienced
details ‘ will be enabled dynamically
public void enableExpSection(){
if(ew.isExperienced)
flag=true;
else
flag=false;
}

//Adding the employee record into list of wrapper


public void submit(){
empWrapList.add(ew) ;
ew = new EmployeeWrap();
}
}

Visualforce Page
<apex:page controller="EmployeeMainCls">

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 70


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

<apex:form >
<apex:pageBlock tabStyle="lead">
<apex:commandButton action="{!submit}" value="submit" reRender="res"/>
<apex:pageBlockSection title="Personal Details">
<apex:pageBlockSectionItem >
<apex:outputLabel >Name</apex:outputLabel>
<apex:inputText value="{!ew.Name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Phone</apex:outputLabel>
<apex:inputText value="{!ew.Phone}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:ou
tputLabel >Email</apex:outputLabel>
<apex:inputText value="{!ew.Email}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Is Experienced?</apex:outputLabel>
<apex:inputCheckbox value="{!ew.isExperienced}">
<apex:actionSupport event="onclick" action="{!enableExpSection}"
reRender="exp"/>
</apex:inputCheckbox>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:outputPanel id="exp" > <!—outputPanel is used to group the other components -->
<apex:pageBlockSection title="Experienced Details" rendered="{!flag}">
<apex:pageBlockSectionItem >
<apex:outputLabel >Company</apex:outputLabel>
<apex:inputText value="{!ew.Company}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:outputPanel>
</apex:pageBlock>

<apex:outputPanel id="res">
<apex:pageBlock title="Details:" rendered="{!empWrapList.size > 0}">
<apex:dataTable value="{!empWrapList}" var="e" frame="border" rules="rows" cellpadding="2">
<apex:column headerValue="Name" value="{!e.Name}"/>
<apex:column headerValue="Phone" value="{!e.Phone}"/>
<apex:column headerValue="Email" value="{!e.Email}"/>
<apex:column headerValue="Company" value="{!e.Company}"/>
</apex:dataTable>
</apex:pageBlock>
</apex:outputPanel>
</apex:form>
</apex:page>

Note: In above code, the actionSupport component is used to add AJAX functionality to component inputCheckBox
so that we user click on it, the apex method enableExpSection is called and turn the flag to true and reRender the
<apex:outputPanel id="exp" >
<apex:pageBlockSectionItem >
<apex:outputLabel >Is Experienced?</apex:outputLabel>
<apex:inputCheckbox value="{!ew.isExperienced}">
<apex:actionSupport event="onclick" action="{!enableExpSection}" reRender="exp"/>

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 71


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

</apex:inputCheckbox>
</apex:pageBlockSectionItem>
14.4 EXERCISE – LIST - ACTIONSUPPORT
1. Create a VF page to get employee details such as personal and experience details in two different sections.
iv. Display only the personal details first like name, phone, email and isExperienced values
v. Display the section ‘Experienced Details’ only when IsExperienced checkbox is enabled in previous
section.
vi. Include a button submit in the page so that when user clicks on it, the employee details entered must
be displayed in another block.

UI for reference

2. Create a wrapper class with details of employee such as name, phone, email, isExperienced, company.
3. Create a main class “EmployeeMainCls “
Variable declarations:
Name : Purpose
EmployeeWrap ew : To get input for the employee wrapper
List<EmployeeWrap>
empWrapList : To create list of employee records in apex so that we can
display in VF page after adding employee record
Boolean flag : To use in rendered attribute of section ‘employee details’

There are two sections such as Personal Details and Experienced Details. When the page is loaded, display only the
Personal Details in the beginning. The section Experienced details should be displayed to get company details only
when the isExperienced checkbox is enabled.

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 72


CapitalInfo Apex Notes Part1 RANJITH KRISHNAN (sfdcmeet@gmail.com)

RANJITH KRISHNAN (sfdcmeet@gmail.com) Page 73

Potrebbero piacerti anche