Professional Documents
Culture Documents
Apex Part 1
Apex Part 1
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;}
Purpose of keyword:
get and set keyword defines whether the variable is readable or writeable one.
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
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 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 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 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;}
<apex:pageBlockButtons location="top">
<apex:commandButton value="show" action="{!show}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
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;}
VF Page
<apex:page controller="CalcClass">
<apex:form >
<apex:pageBlock tabStyle="Lead" id="pb">
<apex:pageBlockButtons >
<!-- reRender : it requires id of another component
<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>
Example:
Account a;
Contact c;
Opportunity op;
Loan_c ln;
Payment__c py;
Customer__c cust;
Training__c tr;
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';
FORMAT 2:
Contact c1 = new Contact();
c1.lastName = 'babu';
c1.email = '[email protected]';
FORMAT1 takes only one line of code compared to FORMAT2. So format1 is preferred when we need to create
multiple records.
Please note that the variable ‘a’ is a local variable and hence the field values will NOT be stored into the account
object.
insert sObjectVariable;
eg.,
Contact c1 = new Contact();
c1.lastName = 'babu';
c1.email = '[email protected]';
insert c1;
Example:
public class AccountClass {
public String accName {get; set;} public String accIndustry {get; set;}
public Decimal accRevenue {get; set;}
VF Page:
<apex:page controller="AccountClass">
<apex:form >
<apex:pageBlock title="Account Entry">
<apex:pageBlockButtons location="top">
Example:
public class ApexAccount {
public Account acc {get; set;}
public Contact con {get; set;}
public Position__c pos {get; set;}
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}"/>
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();
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
Apex Controller:
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error Message.');
ApexPages.addMessage(myMsg);
(Or)
5.1 Example
public with sharing class messageCont {
public string name {get; set;}
public string msg;
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.
In the above cases, the accountID is called Relationship field in child object.
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;}
<apex:page controller="AccountContactCont">
<apex:form >
</apex:form>
</apex:page>
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
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 :
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 |
-------------------------------------------------
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;
Account[] accounts;
Contact[] contacts;
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 |
-----------------------------
Example:
1. Write a array to store names of the students.
String[] studentNames = new String[3];
studentNames[0] = 'Ranjith';
studentnames[1] = 'Ram';
//output
0 1 2
(Ranjith, Ram, null)
cities[0] = 'hyd';
//Output
(1001, 1002, 1001, 1003, 99)
salaries[0] = 1000;
salaried[1] = 4000;
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
Decimal[] salaries = new Decimal[]{4000.00, 500.500, 4005.60};
Examples
String[] productNames = new String[]{'mobile','laptop','mouse'};
i. display the 2nd productname
ii. display the 3rd product name.
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.
studentNames[0] = 'Ranjith';
studentnames[1] = 'Ram';
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.
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
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.
i=1
for(
1
)
0 1 2 3 4
---------------------------------------------
| hyd | chn | pune | bng | dlh |
---------------------------------------------
cities.size() => 5
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]);
}
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'};
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};
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;
for{
totalSalary = 4000 + 4000; 8000
}
i = 3;
for{
TotalSalary = 8000 + 5000; 13000
}
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
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.
Hence, we need not initialize the counter and initialize like in the case of traditional for loop.
Example:
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;
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);
}
for(Integer i : numbers){
System.debug(i);
}
Integer total = 0;
for(Integer i : numbers){
total = total + i;
}
System.debug('total ' + total);
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'
for(String i: industries){
if(i == 'apparel )
System.debug(i);
}
0 1 2 3 4
--------------------------------------------------------
| null | null | null | null | null |
--------------------------------------------------------
rollNos[0] = 3;
rollNos[1] = 4;
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';
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
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
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};
ii. store the lead record into another variable if rating is cold.
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 );
}
//static initialization
Opportunity[] opps = new Opportunity[]{op1, op2, op3};
Example 1: Declare the array of names and store the values 'aaa',''bbb',''ccc', 'ddd'
for(String s: names){
System.debug(s);
Exercise 3: Declare the array of industries such as 'energy' 'education', 'apparel', 'technology';
=========================================================
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
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
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.
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:
List of cities
List<String> cities = new List<String>();
Output:
cities :: (hyd, chn, pune, dlhi, noida, bnlg)
2. get(index) => to get the element from list based on specified index.
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));
3. remove(index) => to remove the element from the list based on index
0 1 2 3 4
----------------------------------------------------
| ram | siva | reddy | ranjith | shravya |
-----------------------------------------------------
Example:
Declare list of productNames and initialize with 5 products
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 - 2055
empNos.add(2055);
0 1 2 3 4 5
------------------------------------------------ ---------
| 1001 | 2002 | 3003 | 4004 | 5005 | 2055 |
----------------------------------------------------------
0 1 2 3 4 5 6
------------------------------------------------ --------------------
| 1001 | 3055 | 2002 | 3003 | 4004 | 5005 | 2055 |
----------------------------------------------------------------------
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!');
for(variable : array/list/set){
//logic
}
for(String c : courseNames ){
System.debug(c);
}
studentNos2.Sort();
System.debug('after sorted:: ' + studentNos2);
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.
op2.CloseDate = Date.newInstance(2019,10,25);
iii. display opportunity record in the log one by one from the oppList
for(Opportunity o: oppList) {
System.debug(o);
}
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>();
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
iv. Get all the company names into another collection if lead source is email.
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
10. SET
Collection of UNIQUE elements
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);
numbers2.addAll(numbers1);
System.debug('after copied :: ' + numbers2);
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 [email protected] 1000
Reddy 6888 [email protected] 2000
Sam 7979 [email protected] 3000
Ranjith 8080 [email protected] 2000
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();
}
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
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
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();
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);
}
key: String
value: account
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
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}}
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()){
ratings.add(a.rating);
}
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);
}
for(Opportunity o: opps){
oppMap2.put(o.stageName, o.Amount);
}
namesList.add(names);
namesList.add(newNames);
0 1
-----------------------------------------
List<String > | List<String>
(names) | (newNames)
----------------------------- -----------
List<String> names1 = nameList .get(0);
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
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
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
Input Data
Name: Order Table
OrderID CustomerName Price
OR001 Ranjith 100
OR002 Sam 200
OR003 Savitha 100
OR004 David 150
OR005 Sam 300
customers.add('Ranjith');
*******************************
2. Create a list of orderIds and add all the order ids into the list
using format1:
using format2:
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);
}
iii. get the customer name in index 2 and store into another string variable
using get(index):
String cust1 = customers.get(2);
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'.
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)
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);
x. Sort the list customers and display the final list into the log.
customers.sort();
System.debug('after sorted the names : ' + customers) ;
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();
The above components can also be used to iterate the list from apex as below.
Apex class
public List<String> customers {get; set;}
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>
</apex:pageBlock>
</apex:page>
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>
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'.
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');
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>
Integer i = 4;
List<Account> accs = [Select name, phone, industry, rating From Account] // in apex
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'
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
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'
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();
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){
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>
Example:
public class AccountWrapper {
public Account a;
public Boolean flag;
}
Initializing
accWrap = new AccountWrapper();
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;}
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 ContactCont(){
//memory allocation
conWrapList = new List<ContactWrapper>();
selectedContacts = new List<Contact>();
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"/>
<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 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);
}
}
<apex:page controller="OppController">
<apex:form >
<apex:pageBlock >
<apex:commandButton value="Open Opps"/>
<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
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
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'};
}
//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: <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: <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>
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
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
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 >
<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.
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;
}
Visualforce Page
<apex:page controller="EmployeeMainCls">
<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"/>
</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.