You are on page 1of 169

Contents

Setter and Getter method: ..................................................................................................................... 8


Constructor and methods: ...................................................................................................................... 8
Example1: Display data in VF Page ..................................................................................................... 8
Example2: Display data in VF Page and reassign the value by calling a function ............................... 8
Example3: Input value from VF page and calculation in Apex class (Add 2 numbers) ....................... 8
Example 4: calling a method from a method within single class ........................................................ 9
Example 5: Display Error and success message in VF page .............................................................. 10
Creation of Sobject: .............................................................................................................................. 11
Example1: Display standard fields and buttons of Lead in custom VF Page using standard
controller........................................................................................................................................... 11
Example2: Display standard fields and buttons of Lead in custom VF Page using controller .......... 11
Page Reference ..................................................................................................................................... 12
Example1: Page Reference ............................................................................................................... 12
Example2: Dynamic Page Reference................................................................................................. 13
Multiple Objects in a VF Page ............................................................................................................... 13
Wrapper Class ....................................................................................................................................... 14
Example1: Multiple Wrapper Classes in single apex class ................................................................ 14
Example2: Multiple Wrapper Classes in single apex class with Logic ............................................... 15
Example3: Nested Wrapper Classes in single apex class with Logic ................................................. 16
Example4: Nested Wrapper Classes with Sobjects in single apex class and creating record in
multiple Sobjects............................................................................................................................... 18
Arrays: ................................................................................................................................................... 19
Example1: Assigning and displaying Array Elements ........................................................................ 19
Example2: Methods of Arrays........................................................................................................... 19
List: ........................................................................................................................................................ 21
Example1: Create a List of Account , Read all the existing Accounts and display in VF Page........... 22
Example2: Create List of Integers and print their sum in the VF Page ............................................ 22
Example3: Create List of Integers and print max value in the VF page ............................................ 23
Example 4: : Create a Wrapper class list and add the record and display in the VF page ................ 23
Example 5: Create a Wrapper class list and add the record from VF page and display in VF page.. 24
Example 6: Create a Wrapper class list and add the record from VF page, display in VF page and
deleting the selected records ........................................................................................................... 25
Example 7: Create a Wrapper class list and add the record from VF page, display in VF page and
deleting the selected records, Editinging the record, updating the record and display the deleted
recored in delete block and selecting all the records with single checkbox..................................... 26
Set ......................................................................................................................................................... 31

pg. 1
Example1: Searching a specific record by number and displaying in the VFpage dynamically. ....... 31
Map: ...................................................................................................................................................... 32
Example 1: Performing creating, deleting, undeleting, searching, save and new, save and edit in
Map using a VF page ......................................................................................................................... 32
SOQL (Salesforce Object Query Language): .......................................................................................... 35
Example1: Write a query to fetch name, phone , industry and rating from accounts and display in
VF page using Static and Dynamic operation(limits,data etc) .......................................................... 35
Example2: Fetching account records and displaing in VF page, performing operation Search,
delete, undelete using WRAPPER Class. In this program there is a connection between records and
checkboxes. Select all checkbox’s using 1 checkbox. ....................................................................... 37
Example2: Displaying the Industry values as picklist item in VFPage. Based on the selected picklist
corresponding records will be displayed automatically in VF page.(action support)....................... 39
Example3: Create picklist with date options and display records based on selected picklist item.. 40
Example3: Using PaneGrid and multiselect picklist and add /delete the options ............................ 41
Example4:Dependent Picklist field ................................................................................................... 43
Example 6:Dynamic picklist which is populated based upon the selected checkbox ...................... 45
Parent Child SOQL ................................................................................................................................. 47
Example1:Displaying Account records with correspondind contact records.(Using Repeat) .......... 47
Example2:Displaying parent child relations in Custom objects ........................................................ 47
Child To Parent in SOQL ........................................................................................................................ 48
Example1:Child to Parent relation in SOQL on Standard Objects .................................................... 48
Example2:Child To Parent in Custom Objects .................................................................................. 49
Example3: Display child contacts for the corresponding selected parent record from the picklist. 49
Example 4: Retrieving the field values of child records for the corresponding parent record
(Retrieving field names of an Object) ............................................................................................... 50
Aggregate Function: .............................................................................................................................. 52
Example1: Aggregate Function: count,sum,min,max,avg ................................................................ 52
DML: Data manipulation Language....................................................................................................... 53
DML Types (Atomic): if any one record fails total operation will fail. .............................................. 53
INSERT ................................................................................................................................................... 53
Example1: Create an Account and contact record reading from VF page and use pagereference to
go to account record (no relation between account and contact) . ................................................. 53
Example2: Create an Account and contact record reading from VF page and use pagereference to
go to account record (Relation between account and contact) . ..................................................... 54
Example3: create parent child relation in custom object. ................................................................ 56
UPDATE: ................................................................................................................................................ 57
Example1: update Rating=warm for account records created today. .............................................. 57
Delete .................................................................................................................................................... 60

pg. 2
Example1: Delete accounts who’s Industry is Education and Rating is HOT. ................................... 60
Example2: Transfer child contact of a selected account to another account and delete the account.
.......................................................................................................................................................... 61
Undelete ............................................................................................................................................... 62
Example1: Undeleting account records from recycle bin. ................................................................ 62
Example:insert,update,delete,edit,save in one program ................................................................. 63
TRY CATCH and SetSavePoint and RollBack. ..................................................................................... 65
NON ATOMIC DML: ............................................................................................................................... 66
Insert/update (Non-atomic).................................................................................................................. 66
Example1: inserting the records in non atomic mode and finding the ids of successful records and
Errors................................................................................................................................................. 66
Example2: Update an existing record using non atomic DML and get the record ids and Error. .... 68
Delete (Non-atomic) ............................................................................................................................. 69
Example:Delete specified records from database using NON-Atomic DML ..................................... 69
UPSERT(NON-ATOMIC) ......................................................................................................................... 70
Example:performing non atomic upsert ........................................................................................... 70
UNDELETE(NON-ATOMIC)..................................................................................................................... 71
Example:performing non atomic undelete ....................................................................................... 71
DELETE RECYCLEBIN(NON_ATOMIC) .................................................................................................... 72
Example:performing non atomic delete recyclebin......................................................................... 72
TRIGGERS .............................................................................................................................................. 73
Trigger Type: ..................................................................................................................................... 74
Trigger Events: These are the events that will fire the triggers when DML is performed. ............... 74
Trigger Context Variables:................................................................................................................. 75
INSERT TRIGGER: ................................................................................................................................... 78
Before Insert: .................................................................................................................................... 78
Example1: Whenever new account is created with industry as banking then set ownership as
private. .............................................................................................................................................. 78
Apex Trigger: .................................................................................................................................... 78
Example2: Whenever new Account is created with Industry as EDUCATION and RATING as Warm.
Then create new opportunity with Opportunity name as account name and other details. .......... 78
Apex Trigger...................................................................................................................................... 78
Example3: When a new Contact is inserted with out Account then throw error message............ 79
Example3: When a new Account is inserted with Industry as banking assign the owner as
'Ramana p'......................................................................................................................................... 79
After Insert: ....................................................................................................................................... 80
If you want to modify the records which are in trigger.new, we can perform DML operation. ...... 80

pg. 3
Example1: Whenever new Account is created with Industry as EDUCATION and RATING as Warm.
Then create new CHILD opportunity with Opportunity name as account name and other details to
account.............................................................................................................................................. 80
Example2:when ever new account is created with annual revenue more thhan 5lak then add
“Ramana P” as a AccountTeamMember........................................................................................... 81
Example 4: When ever a new contact is created submit the record for approval to ‘Ramana P’ .... 82
Example 5: When a new contact is created for an existing account then set contact of the
otherphone as account phone. ......................................................................................................... 83
TASK ...................................................................................................................................................... 84
Example6: When a new Account is created with Account Type as prospect then Create new Task
for the ‘’Ramana P” of the record . ................................................................................................... 84
Example7: When a new Account is created with Account Type as prospect then Create new Task
for the “Ramana P” of the record and send email alert to the “Ramana P”. ................................... 85
Example8:when ever new lead is created then send a mail to customer and owner. ..................... 85
BEFORE UPDATE.................................................................................................................................... 86
Example1:when ever industry is chaging to banking update phone............................................... 86
Example2:when ever industry is changed to banking make “ramana P” as owner and send task and
Email to “ramana P”.......................................................................................................................... 87
Example2:when ever account ownership is changed from public to private update a phone. ....... 88
AFTER UPDATE ...................................................................................................................................... 89
Example1:when ever the opportunity stagename is modified to closed Won and amount is more
than 1000 then share the record to” ramana P”.(calling apex class from trigger)........................... 90
Example2:When ever an account phone is modify update all the contacts of the account ............ 92
 .contacts other phone as oldphine of account ......................................................................... 92
 .contacts mobile phone as newphone of account .................................................................... 92
Delete .................................................................................................................................................... 93
Before Delete: ................................................................................................................................... 93
Example1:If you delete any account record corresponding child contact records to be assigned to
a particular account(Salman). ........................................................................................................... 93

94
AFTER DELETE ................................................................................................................................... 94
UNDELETE(After Undelete) ................................................................................................................... 95
Example:when ever undelete the account records from recyclebin update the active field as “yes”.
.......................................................................................................................................................... 95
Email Services........................................................................................................................................ 96
Outbound Email Services : If you are sending an email from salesforce to external system. .......... 96
Single Email Services: ........................................................................................................................ 96

pg. 4
Example 1: Sending emails to the contacts which are created today. Which includes Sending plain
body, HTML body, HTML Template, and sending attachments. ...................................................... 96
Example2:sending emails based on email field of account object. .................................................. 98
Mass Email Services .......................................................................................................................... 99
Example1: Sending Mass Email to contact object using HTML template ......................................... 99
INBOUND EMAIL SERVICES: : If you are receiving an email from external system to salesforce . . 100
Example:when ever email received from external system to salesforce then create a new account
with email details. ........................................................................................................................... 102
ASYNCHRONOUS OPERATIONS: .......................................................................................................... 102
Future Method .................................................................................................................................... 102
Example1: calling Future method and an apex method combindly from a single method. .......... 103
Example 2: Passing IDs to the apex method and Future method for execution. ........................... 104
Mixed DML Exception: .................................................................................................................... 104
Example1: if we use Setup and Non setup operation in a single code we will get DML
Exception.The following code demonstrate and resolve the issue. ............................................... 105
QUEUABLE APEX ................................................................................................................................. 108
Example:With Queueable apex update the Account records and assign the jobid to description
field of account ............................................................................................................................... 108
Example2: Chaining Apex classes and retrieving ids of the Queueable apex. ................................ 109
GOVERNING LIMITS: ........................................................................................................................... 110
SOQL Governing Limits: .................................................................................................................. 110
DML Governing Limits: .................................................................................................................... 110
Maximum no records on which DML can be performed is 10000 ................................................. 111
BATCH APEX: ....................................................................................................................................... 111
Start Method:.................................................................................................................................. 112
Execute Method: ............................................................................................................................. 112
Finish Method: ................................................................................................................................ 112
Limits of Batch Apex: ...................................................................................................................... 113
Example1:Fetch account records and update some fields and send the email to account holder.
........................................................................................................................................................ 113
Example2:Updating and inserting the more number of records.(Multiple DML) .......................... 114
Example2: Create a batch Apex which fetch all the account Records from Account which are
owned by the user whose profile is System Admin and re-assign to User whose profile is ‘Ramana
P’ ..................................................................................................................................................... 115
Example 3: Create batch apex with takes the query using construtor and update phone and Email
field as batch update...................................................................................................................... 115
Example4: Coverting VF page to PDF based on the Query and attaching to the record. ............... 116

pg. 5
Example:Fetch the records of the selected user and send mail with PDF attachment which
contains all the records (which are fetched) yet to be tested ........................................................ 117
Stateful Interface (in batch apex): ...................................................................................................... 118
Example1: Create a custom object “optytemp” with custom field “Totalamount”. ...................... 118
Summarize the amount of all the opportunities and create a new optytemp record with amount as
summarized value of opportunity .................................................................................................. 118
Example 2: Calling one batch apex from another and passing the value through constructor. .... 119
Schedule Apex: .................................................................................................................................... 121
Example 1: Scheduing the apex at 1:53 PM on 7th Dec 2017, for Deleting contacts which are
created today .................................................................................................................................. 121
Example2:Calling batch apex from schedule apex,and performing different dml operations. ...... 122
Example3:Calling Batch apex,Queueable apex,future method from Schedule apex and performing
various DML operations .................................................................................................................. 123
Example4:calling Schedule apex from Batch apex.(here batch job runs immediately and schedule
runs given interval of time). ............................................................................................................ 125
Example5:calling schedule apex from schedule apex . ................................................................... 126
Example6:Calling schedule apex fromQueueabe apex. .................................................................. 128
EXTENSIONS ........................................................................................................................................ 130
STANDARD CONTROLLER .................................................................................................................... 132
Example1:Customizing “new”button with custom vf page in account object without extensions.
........................................................................................................................................................ 132
Example2:creating a functionality of “save&New” Button using Extensions(We cannot retrieve
existing save&new functionality ). .................................................................................................. 133
Example3:In account detail page create a button”Delete contacts” which displays and delete the
corresponding contacts of the particular account record. ............................................................. 135
Example4:Create a button in contact detail page(AccountDetails) which display the correspong
account detais along with the contact details. ............................................................................... 137
Example5: Create a button in contact detail page(AccountDetails) which display the correspong
account detais along with ”ALL” the corresponding contact records. ........................................... 139
Example6:Overriding a “new” lead Button with custom functionality(Find duplicate before
inserting ). ....................................................................................................................................... 140
Example 7: override “New”button of opportunity object with custom functionality. Add account
with corresponding opportunity and lead records. ........................................................................ 142
STANDARDSETCONTROLLER: .............................................................................................................. 144
Pagenation: ..................................................................................................................................... 144
Example1: extract all the opportunity record and display the records in the VF page as a set of 5
records. And add First,Last,next, previous buttons. ....................................................................... 145
Example2:Parent child with pagination .......................................................................................... 146

pg. 6
Example3:Delete the selected records from the list view page from account object using
standardSetController..................................................................................................................... 147
Example4: create a button in lead list view page which updates the seleted records with Rating as
‘cold................................................................................................................................................. 149
Example5:Create a button to share selected accountrecord to other user(‘Ramana P’ ................ 150
SCHEMA PROGRAMMING ................................................................................................................... 152
Example1:How to get the properties of an object(Account). ......................................................... 153
Example2:Fetch all the fields from Object(Account) and display in picklist. .................................. 154
Example3:Fetch all the childobjects of parent object(Account). .................................................... 155
Example4:Fetch the values of industry picklist and Display picklist in VF Page. ........................... 155
Example5:Fetch all the objects in organization and display in picklist. .......................................... 156
Example7: fetch all the objects from Org and display in a picklist, display the corresponding child
for the selected objects in picklist and for selected child object display the fields in another
picklist. ............................................................................................................................................ 158
Example 8: Fetch all the custom objects in the organization and display in the picklist................ 159
Flows and Plugins ................................................................................................................................ 160
Flows: .............................................................................................................................................. 160
Plugin: ............................................................................................................................................. 160
Process [Plugin] ............................................................................................................................... 160
Process.Plugindescriberesult: ......................................................................................................... 161
Process.plugindescriberesult.inputparameter ............................................................................... 161
Process.plugindescriberesult.outputparameter ............................................................................. 161
Process.pluginrequest..................................................................................................................... 162
Process.pluginresult. ....................................................................................................................... 162
Learnings:I ........................................................................................................................................... 169

pg. 7
Setter and Getter method:
Getter Method: Used to read the value stored in the variable and display in the VF Page.
Setter Method: Used to read the value from VF Page and store data to the variable in the apex class.

Constructor and methods:


This is a special method defined with same class name.
1. It is used to initialize the data members of the class.
2. It will not have any return type.
3. Constructor will invoked only one at the time of creating an object.
Example1: Display data in VF Page
Apex Class:: VF Page::
public class StudentExample { <apex:page controller="StudentExample">
public String name {set;get;} Name :{!name }<br/><br/>
public String branch {set;get;} Branch:{!branch}<br/><br/>
public String city {Set;get;} City : {! city } <br/><br/>
public StudentExample(){ </apex:page>
name='Satish Myla'; Output:
branch='SRNagar'; Name :Satish Myla
city='Hyd';
} Branch:SRNagar
}
City : Hyd
Example2: Display data in VF Page and reassign the value by calling a function
Apex Class::
public class StudentExample { <apex:page controller="StudentExample">
public String name {set;get;} <apex:commandbutton value=”call”
public String branch {set;get;} action=”{!callme}” />
public String city {Set;get;} Name :{!name }<br/><br/>
public StudentExample(){ Branch:{!branch}<br/><br/>
name='Satish Myla'; City : {! city } <br/><br/>
branch='SRNagar'; </apex:page>
city='Hyd'; Output:
} Name :Satish Myla
public void callme(){ Branch:SRNagar
name='Ravi'; City : Hyd
branch='LBNagar'; Oncliking “call” button
city='Hyd' Name :Ravi
Branch:LBNagar
} City : Hyd
Example3: Input value from VF page and calculation in Apex class (Add 2 numbers)
Apex Class
public class Add {
public integer aval {set;get;}
public integer bval {set;get;}
public integer cval {set;get;}
public void add(){
cval=aval+bval;
}
public void reset(){

pg. 8
aval=null;
bval=null;
cval=null;
}
}
VF Page
<apex:page controller="Add" >
<apex:form>
<apex:commandbutton value="ADD" action="{!add}" rerender="pb"/>
<apex:commandbutton value="Refresh" action="{!reset}" rerender="pb"/>
<apex:pageblock Title="Ravi" id="pb" >
<apex:pageBlockSection columns="1" >
<apex:pageBlockSectionItem>
<apex:outputLabel> Aval</apex:outputLabel>
<apex:inputtext value="{!aval}"></apex:inputtext>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel > Bval</apex:outputLabel>
<apex:inputtext value="{!bval}"></apex:inputtext>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel> Cval</apex:outputLabel>
<apex:inputtext value="{!cval}"></apex:inputtext>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

Example 4: calling a method from a method within single class


Apex Class
public class ravi1 {
public integer aval {set;get;}
public integer bval {set;get;}
public integer cval {set;get;}
public integer dval {set;get;}
public void m1(){
aval=10;
bval=20;
m2();
}
public void m2(){
cval=30;
dval=40;

pg. 9
}
}
VF Page
<apex:page controller="ravi1">
<apex:form>
<apex:commandButton value="m1" action="{!m1}"/><br/><br/>
<apex:outputText value="{!aval}"></apex:outputText><br/><br/>
<apex:outputText value="{!bval}"></apex:outputText><br/><br/>
<apex:outputText value="{!cval}"></apex:outputText><br/><br/>
<apex:outputText value="{!dval}"></apex:outputText><br/><br/>
</apex:form>
</apex:page>
Output: after pressing m1 button

Example 5: Display Error and success message in VF page


Apex Class
public class kotesh {
public decimal exp {set;get;}
public decimal sal {set;get;}
public decimal bonus {set;get;}
public void calculate(){
if(exp!=null && exp>0){
if(exp>5) { sal=50000; bonus=sal*0.10;}
else { sal=30000; bonus=sal*0.10;}
apexpages.Message ss=new apexpages.Message(apexpages.Severity.confirm,'success');
apexpages.addmessage(ss);
} else{
apexpages.Message ms=new apexpages.Message(apexpages.Severity.error,'Experience
value must be entered');
apexpages.addmessage(ms);
}
}
}
VF Page
<apex:page controller="kotesh">
<apex:messages />
<apex:form>
<apex:pageblock title="Kotesh">
Enter Experience <apex:inputText value="{!exp}"/>
<apex:pageblocksection>
Salary <apex:outputText value="{!sal}"></apex:outputText>
</apex:pageblocksection>
<apex:pageblocksection>

pg. 10
Bonus <apex:outputText value="{!bonus}"></apex:outputText>
</apex:pageblocksection>
<apex:commandbutton value="calculate" action="{!calculate}"></apex:commandbutton>
</apex:pageblock>
</apex:form>
</apex:page>
Output

Creation of Sobject:
1. Sobject means Salesforce object.
2. Any object created in salesforce database is called Sobject.
3. It can be a Standard or Custom object.

Example1: Display standard fields and buttons of Lead in custom VF Page using standard controller
VF Page
<apex:page standardController="Lead">
<apex:form>
<apex:commandButton value="save" action="{!save}"/>
<apex:commandButton value="cancel" action="{!cancel}"/>
<apex:pageblock title="Lead">
<apex:pageblocksection columns="3">
<apex:inputfield Value="{!lead.Lastname}"/>
</apex:pageblocksection>
<apex:pageblocksection>
<apex:inputfield Value="{!lead.company}"/>
</apex:pageblocksection>
<apex:pageblocksection>
<apex:inputfield Value="{!lead.Status}"/>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>
</apex:page>
Example2: Display standard fields and buttons of Lead in custom VF Page using controller
Apex Class
public class Ganga {
public lead mylead {set;get;}
public Ganga(){
mylead=new lead();
}
public void create(){
insert mylead;

pg. 11
}
public void refresh(){
mylead=new lead();
}
public void saveandnew(){
insert mylead;
mylead=new lead();
}
}
VF Page:
<apex:page Controller="Ganga">
<apex:form >
<apex:commandButton value="create" action="{!create}"/>
<apex:commandButton value="refresh" action="{!refresh}"/>
<apex:commandButton value="save & new" action="{!saveandnew}"/>
<apex:pageblock title="Lead">
<apex:pageblocksection columns="3">
<apex:inputfield Value="{!mylead.Lastname}"/>
</apex:pageblocksection>
<apex:pageblocksection >
<apex:inputfield Value="{!mylead.company}"/>
</apex:pageblocksection>
<apex:pageblocksection >
<apex:inputfield Value="{!mylead.Status}"/>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>
</apex:page>
Output

Page Reference
It is a predefinced apex class

It is used to refer/transfer the control to a specified page.

It is generally used to navigate from one page to another page.

Syntax:

Pagereference P=new pagereference(URL of page);

Example1: Page Reference

pg. 12
Apex Class:
public class pageRef {
public pagereference pageRef(){
pagereference P=new pagereference('https://www.facebook.com/');
return p;
}
}
VF Page
<apex:page controller="pageRef">
<apex:form>
<apex:commandButton value="pageref" action="{!pageRef}"/>
</apex:form>
</apex:page>
Example2: Dynamic Page Reference
Apex Class
public class shiv {
public account acc {set;get;}
public shiv(){
acc=new account();
}
public pagereference create(){
insert acc;
pagereference p=new pagereference('/'+acc.Id);
return p;
}
}
VF Page
<apex:page controller="shiv">
<apex:form>
<apex:commandButton value="create" action="{!create}"/>
<apex:pageblock>
<apex:inputfield value="{!acc.Name}"></apex:inputfield>
<apex:inputfield value="{!acc.Industry}"></apex:inputfield>
<apex:inputfield value="{!acc.Rating}"></apex:inputfield>
</apex:pageblock>
</apex:form>
</apex:page>

Multiple Objects in a VF Page


Example1:
Apex Page:
public class multipleObjects {
public account acc {set;get;}
public contact con {set;get;}
public opportunity opty {set;get;}
public multipleObjects(){
acc=new account();
con=new contact();

pg. 13
opty=new opportunity();
}
public void create(){
insert acc;
insert con;
insert opty;
}
}
VF Page
<apex:page controller="multipleObjects">
<apex:form>
<apex:commandButton value="create" action="{!create}"/>
<apex:pageblock Title="Account" >
<apex:pageBlockSection collapsible="true" columns="1">
<apex:inputField value="{!acc.name}"/>
</apex:pageBlockSection>
</apex:pageblock>
<apex:pageblock Title="Contact">
<apex:inputField value="{!con.lastname}"/>
</apex:pageblock>
<apex:pageblock Title="Oppertunity">
<apex:inputField value="{!opty.name}"/>
<apex:inputField value="{!opty.stagename}"/>
<apex:inputField value="{!opty.closedate}"/>
</apex:pageblock>
</apex:form>
</apex:page>

Wrapper Class
It is user defined data type.
It is a collection of data members only without methods.

Example1: Multiple Wrapper Classes in single apex class


Apex Class
public class Wrapper1 {
public string name {set;get;}
public Integer age {set;get;}
}
______________________________________________-
public class Wrapper11 {
public decimal sal {set;get;}
public integer exp {set;get;}
public Wrapper1 W1 {set;get;}
public Wrapper11(){
W1=new Wrapper1();
sal=30000;
exp=5;
W1.name='Gangu';
W1.age=50;

pg. 14
}
}
VF Page:
<apex:page controller="Wrapper11">
<apex:form>
Name {!W1.name}<br/>
AGe {!W1.age}<br/>
Sal {!sal}<br/>
Exp {!exp}<br/>
</apex:form>
</apex:page>
Output:
Name Gangu
AGe 50
Sal 30000
Exp 5
Example2: Multiple Wrapper Classes in single apex class with Logic
Apex Class:
public class Wacc {
public string name {set;get;}
public string industry {set;get;}
public String rating {set;get;}
}
public class Wopty {
public string name {set;get;}
public string stagename {set;get;}
public date closedate {set;get;}
}
public class WAccOpty {
public Wacc acc {set;get;}
public Wopty opty {set;get;}

public WAccOpty(){
acc=new Wacc();
opty=new Wopty();
}
public void accs(){
if(acc.industry=='Banking'){
acc.rating='Hot';
} else {acc.rating='cold';}
}
public void optys(){
if(opty.stagename=='close won'){
opty.closedate=system.today();
}else{opty.closedate=system.today()+15;}

}
}
VF Page
<apex:page controller="WAccOpty">
<apex:form>

pg. 15
<apex:pageblock Id="pb">
<apex:commandButton value="accs" action="{!accs}" rerender="pb"/>
<apex:pageblocksection Title="Account" collapsible="false">
<apex:pageBlockSectionItem>
<apex:outputLabel value="Name"></apex:outputLabel>
<apex:inputText value="{!acc.name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Industry"></apex:outputLabel>
<apex:inputText value="{!acc.industry}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="{!acc.rating}"></apex:outputLabel>
</apex:pageBlockSectionItem>
</apex:pageblocksection>

<apex:commandButton value="optys" action="{!optys}" rerender="pb"/>


<apex:pageblocksection Title="Opportunity" collapsible="false">
<apex:pageBlockSectionItem>
<apex:outputLabel value="Name"></apex:outputLabel>
<apex:inputText value="{!opty.name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="stagename"></apex:outputLabel>
<apex:inputText value="{!opty.stagename}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="{!opty.closedate}"></apex:outputLabel>
</apex:pageBlockSectionItem>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

Example3: Nested Wrapper Classes in single apex class with Logic


Apex Class:
public class Wacc {
public string name {set;get;}
public string industry {set;get;}
public String rating {set;get;}
}
public class Wopty {
public string name {set;get;}
public string stagename {set;get;}

pg. 16
public date closedate {set;get;}
public Wacc acc {set;get;}
}
public class WAccOpty {
public Wopty opty {set;get;}
public WAccOpty(){
opty=new Wopty();
opty.acc=new Wacc();
}
public void accs(){
if(opty.acc.industry=='Banking'){
opty.acc.rating='Hot';
} else {opty.acc.rating='cold';}
}
public void optys(){

if(opty.stagename=='close won'){
opty.closedate=system.today();
}else{opty.closedate=system.today()+15;}
}
}
VF Page:
<apex:page controller="WAccOpty">
<apex:form >
<apex:pageblock Id="pb">
<apex:commandButton value="accs" action="{!accs}" rerender="pb"/>
<apex:pageblocksection Title="Account" collapsible="false">
<apex:pageBlockSectionItem >
<apex:outputLabel value="Name"></apex:outputLabel>
<apex:inputText value="{!opty.acc.name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Industry"></apex:outputLabel>
<apex:inputText value="{!opty.acc.industry}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="{!opty.acc.rating}"></apex:outputLabel>
</apex:pageBlockSectionItem>
</apex:pageblocksection>

<apex:commandButton value="optys" action="{!optys}" rerender="pb"/>


<apex:pageblocksection Title="Opportunity" collapsible="false">
<apex:pageBlockSectionItem >
<apex:outputLabel value="Name"></apex:outputLabel>
<apex:inputText value="{!opty.name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="stagename"></apex:outputLabel>
<apex:inputText value="{!opty.stagename}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >

pg. 17
<apex:outputLabel value="{!opty.closedate}"></apex:outputLabel>
</apex:pageBlockSectionItem>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>
</apex:page>
Output

Example4: Nested Wrapper Classes with Sobjects in single apex class and creating record in
multiple Sobjects
Apex Class:
public class Wstd1 {
public account acc {set;get;}
}
public class Wstd2 {
public contact con {set;get;}
public Wstd1 aa {set;get;}
}
public class Wstd3 {
public Wstd2 bb {set;get;}
public Wstd3(){
bb=new Wstd2();
bb.con=new contact();
bb.aa=new Wstd1();
bb.aa.acc=new account();
}
public Void Create(){
insert bb.aa.acc;
insert bb.con;
}
}
VF Page
<apex:page controller="Wstd3">
<apex:form>
<apex:pageblock >
<apex:commandButton value="save" action="{!Create}"/>
<apex:pageblocksection Title="account">
<apex:inputfield value="{!bb.aa.acc.name}"></apex:inputfield>
</apex:pageblocksection>
<apex:pageblocksection Title="contact">
<apex:inputfield value="{!bb.con.lastname}"></apex:inputfield>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>

pg. 18
</apex:page>
Output

Arrays:
Its is a collection of similar elements.
1. Memory for the elements in the array is allocated sequentially.
2. Once a size of the array is allocated, it cannot grow or reduce.
3. Elements of the array are referred using index.
4. Index value starts with “0”.
Syntax:
Datatype[] arrayname = new datatype[size];
Example: Integer[] Ravi=new Integer[10];

Example1: Assigning and displaying Array Elements


Apex Classs:
public class Array1 {
public integer[] ravi {set;get;}
public Array1(){
ravi=new integer[10];
ravi[0]=0;
ravi[1]=1;
}
}
Apex Page:
<apex:page controller="Array1">
{!ravi[0]}<br/>
{!ravi[1]}<br/>
<!-- {!ravi[2]}<br/>--Error: It will not display because we have not assigned the value-->
{!ravi[1]}<br/>
{!ravi}<br/>
</apex:page>
Output

Example2: Methods of Arrays


Apex Class
public class Array1 {
public integer[] ravi {set;get;}

pg. 19
public boolean bo {set;get;}
public integer siz {set;get;}
public Array1() {
ravi=new integer[5];
ravi[0]=10;
ravi[1]=20;
ravi[2]=30;
ravi[3]=40;
ravi[4]=50;
ravi.add(4,60);// adds at 5th place and 5th place element moves rightside.
}
public void kotesh(){
ravi.remove(3);
}
public void kotesh1(){
ravi.set(2,33);//replaces the element
}
public void kotesh2(){
bo=ravi.isempty();
}
public void kotesh3(){
siz=ravi.size();
}
public void kotesh4(){
ravi.clear();
}
public void kotesh5(){
ravi.add(99);
}
public void kotesh6(){
integer[] kot=new integer[2];
kot[0]=1;
kot[1]=2;
ravi.addall(kot);
}
public void kotesh7(){
ravi.sort();
}
}
VF Page
<apex:page controller="Array1">
{!ravi}<br/>
<apex:form >
<apex:commandbutton value="remove" action="{!kotesh}"></apex:commandbutton>
<apex:commandbutton value="replace" action="{!kotesh1}"></apex:commandbutton>
<apex:commandbutton value="empty" action="{!kotesh2}"></apex:commandbutton>
{!bo}
<apex:commandbutton value="size" action="{!kotesh3}"></apex:commandbutton>
{!siz}
<apex:commandbutton value="clear" action="{!kotesh4}"></apex:commandbutton>
<apex:commandbutton value="add" action="{!kotesh5}"></apex:commandbutton>
<apex:commandbutton value="addall" action="{!kotesh6}"></apex:commandbutton>
{!ravi}
<apex:commandbutton value="sort" action="{!kotesh7}"></apex:commandbutton>
</apex:form>

pg. 20
</apex:page>
Output:
Landing page:

After Pressing Remove button:

After Pressing Replace button:

After Pressing Empty button:

After Pressing Size button:

After Pressing add button:

After Pressing addall button:

After Pressing clear button:

After pressing Sort button:

List:
It is a collection of similar elements.
1. Size of the List can grow or reduce based on the runtime requirement.
2. Elements in the list are referred using index.
3. Index value starts with “0”.

pg. 21
4. List maintain insertion order.
5. List will accept duplicate values.
6. Salesforce has predefined apex class called List.
7. This class has predefined methods to support the operations on the list.
Syntax:
List <Datatype> List name;
Note: Datatype can be primitive , Sobject, apex class, Wrapper.
Example1: Create a List of Account , Read all the existing Accounts and display in VF Page
Apex Class:
public class List_acc {
public List<account> accs {set;get;}
Public List_acc(){
accs=[Select Name,Industry,Phone from account];
}
}
VF Page
<apex:page controller="List_acc">
<apex:form>
<apex:pageblock>
<apex:pageBlockTable Title="account" value="{!accs}" var="a">
<apex:column value="{!a.Name}"/>
<apex:column value="{!a.Industry}"/>
<apex:column value="{!a.Phone}"/>
</apex:pageBlockTable>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

Example2: Create List of Integers and print their sum in the VF Page
Apex Class:
public class List_sum {
public List<Integer> ravi {set;get;}
public integer sum {set;get;}
public List_sum(){
ravi=new List<Integer>();
ravi.add(10);
ravi.add(20);
ravi.add(30);
ravi.add(40);
ravi.add(50);
sum=0;
for(integer i=0;i<ravi.size();i++)
{ sum=sum+ravi[i];}
}
}
VF Page
<apex:page controller="List_sum">
{!sum}

pg. 22
</apex:page>
Output

Example3: Create List of Integers and print max value in the VF page
Apex Class:
public class List_sum {
public List<Integer> ravi {set;get;}
public integer min {set;get;}
public integer max {set;get;}
public List_sum(){
ravi=new List<Integer>();
ravi.add(10);
ravi.add(20);
ravi.add(30);
ravi.add(40);
ravi.add(50);
min=ravi[0];
max=ravi[0];
for(integer i=0;i<ravi.size();i++)
{ if(ravi[i]<min){min=ravi[i];}
if(ravi[i]>max){max=ravi[i];}
}
}
}
VF Page
<apex:page controller="List_sum">
min{!min}
max{!max}
</apex:page>
Output:

Example 4: : Create a Wrapper class list and add the record and display in the VF page
Apex Class:
public class List_W {
public string name {set;get;}
public integer age {set;get;}
}
public class List_W1 {
public list<List_W> lw {set;get;}
public List_W1(){
lw=new list<List_W>();
List_W aa=new List_W();
aa.name='vipin';
aa.age=30;
lw.add(aa);
}
}

pg. 23
VF Page
<apex:page controller="List_W1">
<apex:form>
<apex:pageblock>
<apex:pageblocktable value="{!lw}" var="a">
<apex:column headerValue="name" value="{!a.name}"></apex:column>
<apex:column headerValue="age" value="{!a.age}"></apex:column>
</apex:pageblocktable>
</apex:pageblock>
</apex:form>
</apex:page>
Output

Example 5: Create a Wrapper class list and add the record from VF page and display in VF page
Apex Class
public class List_W {
public string name {set;get;}
public integer age {set;get;}
}
public class List_W1 {
public list<List_W> lw {set;get;}
public string wname {set;get;}
public integer wage {set;get;}
public List_W1(){
lw=new list<List_W>();
}
public void create(){
List_W aa=new List_W();
aa.name=wname;
aa.age=wage;
lw.add(aa);
}
}
VF Page
<apex:page controller="List_W1">
<apex:form>
<apex:pageblock>
Name <apex:inputText value="{!wname}"/>
age <apex:inputText value="{!wage}"/>
<apex:commandButton value="create" action="{!create}"/>
</apex:pageblock>
<apex:pageblock>
<apex:pageblocktable value="{!lw}" var="a">
<apex:column headerValue="name" value="{!a.name}"></apex:column>
<apex:column headerValue="age" value="{!a.age}"></apex:column>
</apex:pageblocktable>
</apex:pageblock>
</apex:form>
</apex:page>

pg. 24
Output

Example 6: Create a Wrapper class list and add the record from VF page, display in VF page and
deleting the selected records
Apex Class:
public class List_Wrapper {
public string name {set;get;}
public integer age {set;get;}
public string city {set;get;}
public boolean F1 {set;get;}
}
public class List_Wrapper1 {
public List<List_Wrapper> W1 {set;get;}
public string Wname {set;get;}
public integer Wage {set;get;}
public string Wcity {set;get;}

public List_Wrapper1(){
W1=new List<List_Wrapper>();
}
public void create(){
List_Wrapper W2=new List_Wrapper();
W2.name=Wname;
W2.age=Wage;
W2.city=Wcity;
W1.add(W2);
}
public void del(){
for(integer c=0;c<W1.size();c++){
if(W1[c].F1==True) {
W1.remove(c);
c--;
}
}
}
}
VF Page;
<apex:page controller="List_Wrapper1" >
<apex:form >
<apex:pageblock Title="Input" >
<apex:pageBlockSection Title="Input">
Name <apex:inputText value="{!Wname}"/>
age <apex:inputText value="{!Wage}"/>
city <apex:inputText value="{!Wcity}"/>
</apex:pageBlockSection>

pg. 25
</apex:pageblock>
<apex:commandButton value="create" action="{!create}"/>
<apex:commandbutton Value="Delete" action="{!del}"></apex:commandbutton>
<apex:pageblock Title="create">
<apex:pageBlockTable value="{!W1}" var="a">
<apex:column >
<apex:inputCheckbox value="{!a.F1}" />
</apex:column>
<apex:column value="{!a.F1}"/>
<apex:column value="{!a.name}"/>
<apex:column value="{!a.age}"/>
<apex:column value="{!a.city}"/>
</apex:pageBlockTable>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

After pressing Delete button

Example 7: Create a Wrapper class list and add the record from VF page, display in VF page and
deleting the selected records, Editinging the record, updating the record and display the deleted
recored in delete block and selecting all the records with single checkbox
Apex Class:
public class List_Wrapper {
public string name {set;get;}
public integer age {set;get;}

pg. 26
public string city {set;get;}
public boolean F1 {set;get;}
}
public class List_Wrapper1 {
public List<List_Wrapper> W1 {set;get;}
public List<List_Wrapper> dell {set;get;}
public string Wname {set;get;}
public integer Wage {set;get;}
public string Wcity {set;get;}
public string sel {set;get;}
public string opt {set;get;}
public integer x {set;get;}
public boolean z {set;get;}
public List_Wrapper1(){
W1=new List<List_Wrapper>();
dell=new List<list_Wrapper>();
}
public void create(){
List_Wrapper W2=new List_Wrapper();
W2.name=Wname;
W2.age=Wage;
W2.city=Wcity;
W1.add(W2);
}
public void del(){
for(integer c=0;c<W1.size();c++){
if(W1[c].F1==True) {
dell.add(W1[c]);
W1.remove(c);

c--;
}
}
}
public void change(){

for(integer c=0;c<W1.size();c++){
if(W1[c].F1==True) {
W1[c].city=sel;
}
}
}
public void edit(){
for(integer c=0;c<W1.size();c++){
if(W1[c].F1==True) {
Wname=W1[c].name;
Wage=W1[c].age;
Wcity=W1[c].city;
x=c;
break;
}

pg. 27
}}
public void saveedited(){
W1[x].name=Wname;
W1[x].age=Wage;
W1[x].city=Wcity;
}
public void sall(){

for(integer c=0;c<W1.size();c++){
W1[c].F1=z;
}}
}
VF Page:
<apex:page controller="List_Wrapper1" >
<apex:form >
<apex:pageblock Title="Input" >
<apex:pageBlockSection Title="Input">
Name <apex:inputText value="{!Wname}"/>
age <apex:inputText value="{!Wage}"/>
city <apex:inputText value="{!Wcity}"/>
</apex:pageBlockSection>
<apex:pageBlock title="change">

<apex:selectlist id="selectcity" value="{!sel}" size="1">


<apex:selectOption itemvalue="hyd" itemlabel="hyd"/>
<apex:selectOption itemvalue="ban" itemlabel="ban"/>
<apex:selectOption itemvalue="che" itemlabel="che"/>
</apex:selectlist>
</apex:pageBlock>
</apex:pageblock>
<apex:commandButton value="create" action="{!create}"/>
<apex:commandButton value="change" action="{!change}"/>
<apex:commandButton value="Edit" action="{!edit}"/>
<apex:commandButton value="saveedited" action="{!saveedited}"/>
<apex:inputCheckbox value="{!z}" >
<apex:actionsupport event="onchange" action="{!sall}">
</apex:actionsupport>
</apex:inputCheckbox>
<apex:commandbutton Value="Delete" action="{!del}"></apex:commandbutton>
<apex:pageblock Title="create">
<apex:pageBlockTable value="{!W1}" var="a">
<apex:column >
<apex:inputCheckbox value="{!a.F1}" />
</apex:column>
<apex:column value="{!a.F1}"/>
<apex:column value="{!a.name}"/>
<apex:column value="{!a.age}"/>
<apex:column value="{!a.city}"/>
</apex:pageBlockTable>
</apex:pageblock>

pg. 28
<apex:pageblock Title="Deleted">
<apex:pageBlockTable value="{!dell}" var="d">
<apex:column value="{!d.F1}"/>
<apex:column value="{!d.name}"/>
<apex:column value="{!d.age}"/>
<apex:column value="{!d.city}"/>
</apex:pageBlockTable>
</apex:pageblock>
</apex:form>
</apex:page>
Output:
Before pressing Change button

After pressing change button.

Before pressing Edit button

After pressing Edit button:

pg. 29
After pressing Saveedited button

After pressing pageblock checkbox(action support)

After Pressing Delete button (displays recored in Deleted block)

pg. 30
Set
1. It is a collection of similar elements.
2. Size of the Set can grow or reduce based on the runtime requirement.
3. Elements in the set are referred using value NOT INDEX
4. Index value starts with “0”.
5. Set maintain insertion order.
6. Set will NOT accept duplicate values.
7. Salesforce has predefined apex class called Set.
8. This class has predefined methods to support the operations on the Set.
9. Set cannot be displayed in PageBlocktable
10. We can display set records by declaring set reference name/variable. Eg. {!a}

Syntax:

Set<Datatype> setname = new Set<Datatype>();

Set<Integer> setname = new Set<Integer>();

Example1: Searching a specific record by number and displaying in the VFpage dynamically.
Apex Class:
public class Set_Example1 {
public string name {set;get;}
public Integer age {Set;get;}
}
public class Set_Example11 {
public set<Set_Example1> S1 {set;get;}
public set<Set_Example1> temp {set;get;}
public Integer count {set;get;}
public Set_Example11(){
S1=new set<Set_Example1>();
temp=new set<Set_Example1>();
Set_Example1 S2=new Set_Example1();
Set_Example1 S3=new Set_Example1();
Set_Example1 S4=new Set_Example1();
Set_Example1 S5=new Set_Example1();

S2.name='Ravi';
S2.age=10;

pg. 31
S1.add(s2);
S3.name='kotesh';
S3.age=20;
S1.add(s3);
S4.name='vipin';
S4.age=30;
S1.add(s4);
S5.name='Gangu';
S5.age=30;
S1.add(s5);
}
public void disp(){
Integer i=0;
for(Set_Example1 a:S1)
{if(i==count) { temp.clear(); temp.add(a);}
i++;
}

}
}
VF Page:
<apex:page controller="Set_Example11">
{!temp}
<apex:form>
<apex:inputText value="{!count}">
<apex:commandButton value="Display" action="{!disp}" />
</apex:inputText>

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

Map:
1. It is a collection of similar elements.
2. It is a key value pair.
3. The size of the map can grow or reduce dynamically based on run time requirement.
4. Key in the map should be unique.
5. Value in the map can be duplicate.

Syntax:
Map <key, value> mapname;

Example 1: Performing creating, deleting, undeleting, searching, save and new, save and edit in
Map using a VF page
Apex class:
public class Map1 {
public map<string,string> ravi {set;get;}
public map<string,string> ravi1 {set;get;}

pg. 32
public string name {set;get;}
public string city {set;get;}
public string find {set;get;}
public string result {set;get;}
public Map1(){
ravi=new map<string,string>();
ravi1=new map<string,string>();
ravi.put('ravi','hyd');
ravi.put('kot','ban');
ravi.put('kotesh','sec');
ravi.put('Gangu','pak');
}
public void create(){
ravi.put(name,city);
}
public void search(){
result=ravi.get(find);
}
public void modify(){
result=ravi.get(find);
name=find;
city=result;
}
public void save(){
ravi.put(name,city);
}
public void savenew(){
ravi.put(name,city);
name=null;
city=null;
}
public void del(){
result=ravi.get(find);
ravi1.put(find,result);
ravi.remove(find);
}
public void undel(){
result=ravi1.get(find);
ravi.put(find,result);
ravi1.remove(find);
}
}
VF Page
<apex:page controller="Map1">
<apex:form>
<apex:pageblock title="input">
<apex:pageblocksection >
Name <apex:inputtext value="{!name}"/>
City <apex:inputtext value="{!city}"/>
<apex:commandButton Value="Create" action="{!create}"/>
</apex:pageblocksection>

pg. 33
</apex:pageblock>

<apex:pageblock title="Display">
<apex:pageblocktable title="Display" value="{!ravi}" var="a">
<apex:column value="{!a}"/>
<apex:column value="{!ravi[a]}"/>
</apex:pageblocktable>
</apex:pageblock>

<apex:pageblock title="search">
<apex:pageblocksection >
Search City by Name <apex:inputtext value="{!find}"/>
Searched City Name <apex:outputtext value="{!result}"/>
<apex:commandButton Value="Search" action="{!search}"/>
</apex:pageblocksection>
</apex:pageblock>

<apex:pageblock Title="Modify">
<apex:pageblocksection >
Enter the record name to be modified <apex:inputtext value="{!find}"/>

<apex:commandButton Value="Edit" action="{!Modify}"/>


<apex:commandButton Value="Save" action="{!save}"/>
<apex:commandButton Value="Savenew" action="{!savenew}"/>
</apex:pageblocksection>
</apex:pageblock>

<apex:pageblock Title="Delete">
<apex:pageblocksection >
Enter the record name to be deleted <apex:inputtext value="{!find}"/>
<apex:commandButton Value="Delete" action="{!del}"/>
<apex:commandButton Value="UnDelete" action="{!undel}"/>
</apex:pageblocksection>
<apex:pageblocktable title="Display" value="{!ravi1}" var="b">
<apex:column value="{!b}"/>
<apex:column value="{!ravi1[b]}"/>
</apex:pageblocktable>
</apex:pageblock>

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

pg. 34
SOQL (Salesforce Object Query Language):
Query: It is a statement which is used to retrieve the data from the object (standard/Custom).
Syntax:
List <subject> listname=[Query];
Eg1: List <account> acc=[Select name, industry from account];

Example1: Write a query to fetch name, phone , industry and rating from accounts and display in
VF page using Static and Dynamic operation(limits,data etc)
-Adding checkboxes in column and header.
Apex Class:
public class SOQL1 {
public list<account> acc {set;get;}
public integer count {set;get;}
public string data {set;get;}
public SOQL1(){
acc=[select name,phone,industry,rating from account];
}
public void Slimit(){
acc=[select name,phone,industry,rating from account Limit:5];
}
public void Dlimit(){
acc=[select name,phone,industry,rating from account Limit:count];
}
public void specific(){

pg. 35
acc=[select name,phone,industry,rating from account where industry='Banking'];
}
public void Dspecific(){
acc=[select name,phone,industry,rating from account where industry=:data];
}
}
VF Page
<apex:page controller="SOQL1">
<apex:form>
<apex:pageblock Title="Actions on Account">

<apex:commandButton value="Limit=5" action="{!Slimit}"/><br/><br/>


Enter the Limit:<apex:inputtext value="{!count}"/>
<apex:commandButton value="Dynamic Limit" action="{!Dlimit}"/><br/><br/>
<apex:commandButton value="Specific_Where" action="{!specific}"/><br/><br/>
Enter the Industry:<apex:inputtext value="{!data}"/>
<apex:commandButton value="Specific_Where_Dynamic"
action="{!Dspecific}"/><br/><br/>

</apex:pageblock >

<apex:pageblock Title="Account">
<apex:pageblocktable Value="{!acc}" var="a">
<apex:column >
<apex:inputcheckbox ></apex:inputcheckbox>
<apex:facet name="Header">
<apex:inputcheckbox ></apex:inputcheckbox>
</apex:facet>
</apex:column>
<apex:column value="{!a.name}" headervalue="Name"/>
<apex:column value="{!a.phone}" headervalue="phone"/>
<apex:column value="{!a.industry}" headervalue="industry"/>
<apex:column value="{!a.rating}" headervalue="rating"/>
</apex:pageblocktable>
</apex:pageblock>

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

Note:
1. Facet is used to display checkbox in header/footer in column.
2. In the above program, there is no connection between records and checkboxs.
3. If you want connection between records and checkboxes use Wrapper class.

pg. 36
Example2: Fetching account records and displaing in VF page, performing operation Search,
delete, undelete using WRAPPER Class. In this program there is a connection between records and
checkboxes. Select all checkbox’s using 1 checkbox.

Apex class:
public class SOQL2 {
public Account acc {set;get;}
public boolean flag {set;get;}
}
public class SOQL22 {
public list<SOQL2> accs {set;get;}
public list<SOQL2> del {set;get;}
public list<Account> a {set;get;}
public boolean f1 {set;get;}
public string find {set;get;}
public SOQL22(){
a=[select name,id,phone,industry from Account];
accs=new List<SOQL2>();
del=new List<SOQL2>();
for(account x:a){
SOQL2 s = new SOQL2();
s.acc=x;
s.flag=false;
accs.add(s);
}
}
public void search(){
a=[select name,id,phone,industry from Account where industry=:find];
accs=new List<SOQL2>();
for(account x:a){
SOQL2 s = new SOQL2();
s.acc=x;
s.flag=false;
accs.add(s);
}
}
public void del(){
for(integer i=0;i<accs.size();i++){
if(accs[i].flag==True){
del.add(accs[i]);
accs.remove(i);
i--;

}
}
}

public void undel(){


for(integer i=0;i<del.size();i++){
if(del[i].flag==True){
accs.add(del[i]);

pg. 37
del.remove(i);
i--;

}
}
}
public void allsel(){
for(integer i=0;i<del.size();i++){
del[i].flag=f1;
}

}
}
VF Page
<apex:page controller="SOQL22" >
<apex:form>
<apex:pageblock>
Enter the Industry <apex:inputtext value="{!find}"/>
<apex:commandbutton value="Search" action="{!search}"/>
</apex:pageblock>

<Apex:pageblock>
<apex:pageblocktable value="{!accs}" var="b">
<apex:column>
<apex:inputcheckbox value="{!b.flag}"/>
</apex:column>

<apex:column value="{!b.acc.name}"/>
<apex:column value="{!b.acc.phone}"/>
<apex:column value="{!b.acc.industry}"/>

</apex:pageblocktable>
<apex:commandbutton value="Delete" action="{!del}"/><br/>

</Apex:pageblock>
<Apex:pageblock Title="Deleted">
<apex:inputcheckbox value="{!f1}">
<apex:actionsupport event="onchange" action="{!allsel}">
</apex:actionsupport>
</apex:inputcheckbox>
<apex:pageblocktable value="{!del}" var="c">
<apex:column>
<apex:inputcheckbox value="{!c.flag}"/>
</apex:column>

<apex:column value="{!c.acc.name}"/>
<apex:column value="{!c.acc.phone}"/>
<apex:column value="{!c.acc.industry}"/>

</apex:pageblocktable>

pg. 38
<apex:commandbutton value="UnDelete" action="{!undel}"/>
</Apex:pageblock>

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

Example2: Displaying the Industry values as picklist item in VFPage. Based on the selected picklist
corresponding records will be displayed automatically in VF page.(action support)
Apex Class:
public class SOQL3 {
public list<account> acc {set;get;}
public set<string> ind {set;get;}
public string ravi {set;get;}
public list<selectoption> option{set;get;}

public SOQL3(){
acc=[select name,phone,industry,rating from account];
ind=new set<string>();
option=new list<selectoption>();
for(account a:acc){
ind.add(a.industry);
}

for(string x:ind){
if(x!=null){
selectoption s=new selectoption(x,x);
option.add(s);
}}
}
public void love(){
acc=[select name,phone,industry,rating from account where industry=:ravi];
}
}
VF Page
<apex:page controller="SOQL3">
<apex:form>
<apex:pageblock>
industry:<apex:selectlist value="{!ravi}" multiselect="false" size="1">
<apex:actionsupport event="onchange" action="{!love}"/>
<apex:selectoptions value="{!option}">
</apex:selectoptions>
</apex:selectlist>

pg. 39
</apex:pageblock>
<apex:pageblock>
<apex:pageblocktable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.phone}"/>
<apex:column value="{!a.rating}"/>
<apex:column value="{!a.industry}"/>
</apex:pageblocktable>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

Example3: Create picklist with date options and display records based on selected picklist item.
Apex Class:
public class SOQL5 {
public list<account> acc {set;get;}
public list<selectoption> ss {set;get;}
public string ravi {Set;get;}

public SOQL5(){
ss=new list<selectoption>();
selectoption s1=new selectoption('none','none');
selectoption s2=new selectoption('Today','Today');
selectoption s3=new selectoption('This_Week','This_Week');
selectoption s4=new selectoption('This_Month','This_Month');
ss.add(s1);
ss.add(s2);
ss.add(s3);
ss.add(s4);
}

public void hyd(){


string qqq='select name from account where createddate='+ravi;
acc=database.query(qqq);
}
}
VF Page
<apex:page controller="SOQL5">

<apex:form >
<apex:pageblock >
<apex:selectlist size="1" value="{!ravi}" >
<apex:selectoptions value="{!ss}">
</apex:selectoptions>
</apex:selectlist>
</apex:pageblock>
<apex:commandButton value="Display" action="{!hyd}"/>

pg. 40
<apex:pageblock >
<apex:pageblocktable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
</apex:pageblocktable>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

Example3: Using PaneGrid and multiselect picklist and add /delete the options
Apex Class:
public class multipic {
public list<string> sel {set;get;}
public list<string> Dsel {set;get;}
public list<selectoption> sellist {set;get;}
public list<selectoption> Dsellist {set;get;}
public list<string> Gangu {set;get;}
public list<string> Mangu {set;get;}
public string del {set;get;}

public multipic(){
sel=new list<string>{'Jan','Feb','Mar','Apr','May','Jun'};
Dsel=new list<string>{'Dec'};
sellist=new list<selectoption>();
Dsellist=new list<selectoption>();
Gangu=new list<string>();
Mangu=new list<string>();
for(string x:sel){
selectoption y=new selectoption(x,x);
sellist.add(y);
}

for(string z:Dsel){
selectoption y1=new selectoption(z,z);
Dsellist.add(y1);
}
del=sellist[0].getvalue();

}
public void add(){
integer i=0;
integer j=0;
for(string f:Gangu){
selectoption op=new selectoption(f,f);
Dsellist.add(op);

pg. 41
for(i=0;i<sellist.size();i++){
for(j=0;j<Gangu.size();j++){
if(Gangu[j]==sellist[i].getvalue()){ sellist.remove(i);}
}
}
}

public void Remove(){


integer i=0;
integer j=0;
for(string f:Mangu){
selectoption op=new selectoption(f,f);
sellist.add(op);
for(i=0;i<Dsellist.size();i++){
for(j=0;j<Mangu.size();j++){
if(Mangu[j]==Dsellist[i].getvalue()){ Dsellist.remove(i);}
}
}
}

}
VF Page:
<apex:page controller="multipic">
<apex:form >
<apex:panelGrid columns="3" id="theGrid" width="800" border="5">
<apex:selectlist value="{!Gangu}" multiselect="true" >
<apex:selectoptions value="{!sellist}"/>
</apex:selectlist>
<apex:pageblock>
<apex:commandbutton value="add" action="{!add}"></apex:commandbutton><br/><br/>
<apex:commandbutton value="Remove" action="{!remove}"></apex:commandbutton>
</apex:pageblock>
<apex:selectlist value="{!Mangu}" multiselect="true">
<apex:selectoptions value="{!Dsellist}"/>
</apex:selectlist>
</apex:panelGrid>
</apex:form>
</apex:page>
Output:

Additional code give by instructor


public class multipic1 {
public list<string> months {set;get;}

pg. 42
public list<string> nsmonths {set;get;}
public list<selectoption> options {set;get;}
public list<selectoption> nsoptions {set;get;}
public list<string> selected {set;get;}
public list<string> nsselected {set;get;}
public multipic1(){
months=new list<string>();
nsmonths=new list<string>{'jan','feb','mar','apr','may','jun'};
options=new list<selectoption>();
nsoptions=new list<selectoption>();
selected=new list<string>();
nsselected=new list<string>();

}
public void getoptions(){
options.clear();
nsoptions.clear();
selectoption op=new selectoption('none','-None-');
if(nsmonths.size()>0){
for(string s: nsmonths){
selectoption s1=new selectoption(s,s);
nsoptions.add(s1);
}
}else{
nsoptions.add(op);
}
if(months.size()>0){
for(string s0: months){
selectoption s2=new selectoption(s0,s0);
options.add(s2);
}
}else{
options.add(op);
}
}
public void addele(){
nsmonths.removeall(selected);
months.addall(selected);
getoptions();
}
public void delele(){
nsmonths.addall(nsselected);
months.removeall(nsselected);
getoptions();
}
}
Example4:Dependent Picklist field
Note:onefield is controlled by another field
Apex Class:
public class Fdependency {
public map<string,list<string>> resmap {set;get;}

pg. 43
public set<string> s1 {set;get;}
public list<string> s2 {set;get;}
public list<selectoption> ss {set;get;}
public list<selectoption> sss{set;get;}
public string selected {set;get;}

public Fdependency(){
resmap=new map<string,list<string>>();
ss=new list<selectoption>();
sss=new list<selectoption>();

list<string> hp=new list<string>{'Srnagar','lbnagar','ameerpet'};


list<string> bp=new list<string>{'btm','marathahalli','bellandhur'};
list<string> cp=new list<string>{'pragathinagar','Beachroad','tnagar'};
resmap.put('hyd',hp);
resmap.put('ban',bp);
resmap.put('che',cp);
s1=resmap.keyset();
for(string s:s1){
selectoption l=new selectoption(s,s);
ss.add(l);
}

}
public void ravi(){
s2=resmap.get(selected);
sss.clear();
for(string s0:s2){

selectoption l1=new selectoption(s0,s0);


sss.add(l1);
}

}
}
VF page:
<apex:page controller="Fdependency" >
<apex:form>
<apex:selectList value="{!selected}" size="1">
<apex:actionSupport event="onchange" action="{!ravi}"/>
<apex:selectOptions value="{!ss}"></apex:selectOptions>
</apex:selectList>
<apex:selectList size="1" >
<apex:selectOptions value="{!sss}"></apex:selectOptions>
</apex:selectList>
</apex:form>
</apex:page>
Output:

pg. 44
Example 6:Dynamic picklist which is populated based upon the selected checkbox
Apex Class:
public class Ex {
public string city {set;get;}
public Boolean flag {set;get;}
}
public class Checkp {
public list<Ex> W1 {set;get;}
public List<selectoption> pick1 {set;get;}
public list<string> selected {set;get;}
public list<string> x1 {set;get;}
public list<string> options {set;get;}
public map<string,list<string>> resmap {set;get;}
public Checkp(){
W1=new List<Ex>();
selected=new list<string>();
options=new list<string>();
X1=new list<string>();
resmap=new map<string,list<string>>();
pick1=new list<selectoption>();
Ex a=new Ex();
a.city='hyd';
a.flag=false;
W1.add(a);
Ex a1=new Ex();
a1.city='ban';
a1.flag=false;
W1.add(a1);
Ex a2=new Ex();
a2.city='che';
a2.flag=false;
W1.add(a2);
list<string> hp=new list<string>{'Srnagar','lbnagar','ameerpet'};
list<string> bp=new list<string>{'btm','marathahalli','bellandhur'};
list<string> cp=new list<string>{'pragathinagar','Beachroad','tnagar'};
resmap.put('hyd',hp);
resmap.put('ban',bp);
resmap.put('che',cp);

}
public void display(){
options.clear();
selected.clear();
for(Ex a:W1){

pg. 45
if(a.flag==true){
selected.add(a.city);
}
}
for(string x:selected){
X1=resmap.get(x);
options.addall(X1);
}
pick1.clear();
for(string m:options){
selectoption s=new selectoption(m,m);
pick1.add(s);
}
}
}
VF page:

<apex:page controller="Checkp" >

<apex:form>
<apex:panelGrid columns="2">
<apex:commandButton value="check" action="{!display}"/>
<apex:pageBlock>
<apex:pageBlockTable value="{!W1}" var="c">
<apex:column >
<apex:inputCheckbox value="{!c.flag}" />
</apex:column>
<apex:column value="{!c.city}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:panelGrid>
<apex:selectList size="1">
<apex:selectOptions value="{!pick1}"></apex:selectOptions>
</apex:selectList>

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

pg. 46
Parent Child SOQL
Example1:Displaying Account records with correspondind contact records.(Using Repeat)
Note:
1.Repeat is used to display child records for every corresponding parent record.
2.The child object name should be plural.(i.e contacts)

Apex Class:
public class PC1 {
public List<Account> acc {set;get;}
public void disp(){
acc=[select name,phone,industry,(select lastname from contacts)from account];
}
}
VF page:
<apex:page controller="PC1" >

<apex:form>
<apex:commandButton value="submit" action="{!disp}"/>
<apex:pageBlock>
<apex:pageBlockTable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.phone}"/>
<apex:column value="{!a.industry}"/>
<apex:column headerValue="Lastname">
<apex:repeat value="{!a.contacts}" var="b">
{!b.lastname}<br/>
</apex:repeat>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

Example2:Displaying parent child relations in Custom objects


Note:
1.Repeat is used to display child records for every corresponding parent record.
2.The child object name should be plural and extended by __r(i.e Courses__r)

Apex Class:
public class PC1 {
public List<Branch__c> acc {set;get;}
public void disp(){

pg. 47
acc=[select name,Date__c,Fee__c,(select name,phone__c from courses__r)from Branch__c];
}

}
VF Page:
<apex:page controller="PC1" >

<apex:form >
<apex:commandButton value="submit" action="{!disp}"/>
<apex:pageBlock >
<apex:pageBlockTable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.Date__c}"/>
<apex:column value="{!a.Fee__c}"/>
<apex:column headerValue="coursesName">
<apex:repeat value="{!a.courses__r}" var="b">
{!b.name}<br/>
</apex:repeat>
</apex:column>
<apex:column headerValue="Phone">
<apex:repeat value="{!a.courses__r}" var="c">
{!c.phone__c}<br/>
</apex:repeat>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

Child To Parent in SOQL


Example1:Child to Parent relation in SOQL on Standard Objects
Apex Class:
public class CP {
public List<Contact> con {set;get;}
public void CP1(){
con=[select Lastname,phone,Account.name,Account.Industry from contact];
}
}
VF Page:
<apex:page controller="CP">
<apex:form>
<apex:commandButton value="submit" action="{!CP1}"/>
<apex:pageBlock>
<apex:pageBlockTable value="{!con}" var="a">
<apex:column value="{!a.lastname}"/>

pg. 48
<apex:column value="{!a.phone}"/>
<apex:column value="{!a.account.name}"/>
<apex:column value="{!a.account.Industry}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

Example2:Child To Parent in Custom Objects


Apex Class:
public class CP {
public List<Course__c> con {set;get;}
public void CP1(){
con=[select name,Date__c,Age__c,Branch__c,Branch__r.name,Branch__r.Fee__c from
Course__c];
}
}
VF Page:
<apex:page controller="CP">
<apex:form>
<apex:commandButton value="submit" action="{!CP1}"/>
<apex:pageBlock>
<apex:pageBlockTable value="{!con}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.Date__c}"/>
<apex:column value="{!a.Age__c}"/>
<apex:column value="{!a.Branch__c}"/>
<apex:column value="{!a.Branch__r.name}"/>
<apex:column value="{!a.Branch__r.Fee__c}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

Example3: Display child contacts for the corresponding selected parent record from the picklist.
Apex class:
public class PCReq {

pg. 49
public List<Account> acc {set;get;}
public list<selectoption> ss {set;get;}
public list<selectoption> sc {set;get;}
public string selected {set;get;}

public PCReq(){
acc=[select name,(select LastName from Contacts) from Account];
ss=new list<selectoption>();
sc=new list<selectoption>();
for(Account a:acc){
selectoption s=new selectoption(a.Name,a.Name);
ss.add(s);
}
}

public void display(){


for(Account a:acc){
if( selected==a.name){
for(contact b:a.contacts){
selectoption s1=new selectoption(b.lastname,b.lastname);
sc.add(s1);
}
}
}
}
}
VF Page
<apex:page controller="PCReq" >

<apex:form >
<apex:commandbutton value="display" action="{!display}"></apex:commandbutton>
<apex:selectList size="1" value="{!selected}">
<apex:selectOptions value="{!ss}"></apex:selectOptions>
</apex:selectList><br/><br/>
<apex:selectList size="1">
<apex:selectOptions value="{!sc}"></apex:selectOptions>
</apex:selectList>
</apex:form>
</apex:page>
Output:

Example 4: Retrieving the field values of child records for the corresponding parent
record (Retrieving field names of an Object)
Apex Class:
public class DMLUpdate2 {
public set<string> keys {set;get;}

pg. 50
public list<account> acc {set;get;}
public list<selectoption> ss {set;get;}
public list<selectoption> sss {set;get;}
public list<selectoption> ssss {set;get;}
public string selected {set;get;}
public string selected1 {set;get;}
public string selected2 {set;get;}
public string v {set;get;}
public DMLUpdate2(){
ss=new list<selectoption>();
sss=new list<selectoption>();
ssss=new list<selectoption>();
acc=[select name,(select name,phone from contacts) from account];
for(Account a:acc){
selectoption s=new selectoption(a.name,a.name);
ss.add(s);
}

}
public void disp(){
sss.clear();
for(Account a1:acc){
if(selected==a1.name){
for(contact c:a1.contacts){
selectoption s1=new selectoption(c.name,c.name);
sss.add(s1);
}
}
}
}
public void fields(){
schema.DescribeSObjectResult result=contact.SobjectType.getDescribe();
map<string,Schema.SObjectField> fldmap=result.fields.getmap();
keys=fldmap.keySet();
ssss.clear();
for(string d:keys){
selectoption s2=new selectoption(d,d);
ssss.add(s2);
}

}
public void fnames(){

for(Account a1:acc){
if(selected==a1.name){
for(contact c:a1.contacts){
if(selected1==c.name){
v=c.phone;
}
}
}

pg. 51
}

}
}
VF page
<apex:page controller="DMLUpdate2" >
{!selected}
{!selected1}
{!selected2}
{!v}
<apex:form >
<apex:pageBlock >
<apex:commandButton value="phone" action="{!fnames}"/>
<apex:selectList size="1" value="{!selected}">
<apex:actionSupport event="onchange" action="{!Disp}"/>
<apex:selectOptions value="{!ss}"></apex:selectOptions>
</apex:selectList>
<apex:selectList size="1" value="{!selected1}" >
<apex:actionSupport event="onchange" action="{!fields}"/>
<apex:selectOptions value="{!sss}"></apex:selectOptions>
</apex:selectList>
<apex:selectList size="1" value="{!selected2}" >
<apex:selectOptions value="{!ssss}"></apex:selectOptions>
</apex:selectList>

</apex:pageBlock>
</apex:form>
</apex:page>
Output

Aggregate Function:
Example1: Aggregate Function: count,sum,min,max,avg
Apex Class:
public class agregate {
public decimal max {set;get;}
public decimal cou {set;get;}
public decimal min {set;get;}
public decimal avg {set;get;}
public decimal sum {set;get;}
public agregate(){
aggregateResult ag=[select
count(Amount__c)cou,Max(Amount__c)max,Min(Amount__c)min,avg(Amount__c)avg,sum(Amou
nt__c)sum from aggregate__c];
max=(decimal)ag.get('max');
min=(decimal)ag.get('min');
avg=(decimal)ag.get('avg');

pg. 52
sum=(decimal)ag.get('sum');
cou=(decimal)ag.get('cou');
}
}
VF Page
<apex:page controller="agregate">
max {!max}<br/><br/>
min {!min}<br/><br/>
avg {!avg}<br/><br/>
sum {!sum}<br/><br/>
cou {!cou}<br/><br/>
</apex:page>
Output:

DML: Data manipulation Language


DML Types (Atomic): if any one record fails total operation will fail.
1. Insert
2. Update
3. Delete
4. Undelete
5. Merge
6. Upsert

INSERT
Example1: Create an Account and contact record reading from VF page and use pagereference to
go to account record (no relation between account and contact) .
Note: In this program there is no relation between account and contact.
Apex class:
public class InsertDML1 {
public account acc {set;get;}
public contact con {set;get;}
public InsertDML1(){
acc=new account();
con=new contact();
}
public pagereference create(){
insert acc;
insert con;
pagereference p=new pagereference('/'+acc.Id);

pg. 53
return p;
}
}
VF page:
<apex:page controller="InsertDML1">
<apex:form>
<apex:pageblock >
<apex:commandButton value="save" action="{!create}"/>
<apex:pageblocksection Title="account">
<apex:inputfield value="{!acc.name}"/>
<apex:inputfield value="{!acc.phone}"/>
<apex:inputfield value="{!acc.Industry}"/>
<apex:inputfield value="{!acc.ownership}"/>
<apex:inputfield value="{!acc.rating}"/>
</apex:pageblocksection>

<apex:pageblocksection Title="Contact">
<apex:inputfield value="{!con.Lastname}"/>
<apex:inputfield value="{!con.phone}"/>
<apex:inputfield value="{!con.firstname}"/>
<apex:inputfield value="{!con.MobilePhone}"/>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

Example2: Create an Account and contact record reading from VF page and use pagereference to
go to account record (Relation between account and contact) .
Note: In this program there is parent child relation between account and contact.
Apex Class:
public class InsertDML1 {
public account acc {set;get;}
public contact con {set;get;}
public InsertDML1(){
acc=new account();
con=new contact();
}
public pagereference create(){
insert acc;
con.AccountId=acc.Id;//This is to create a link between contact(child) and Account(parent)
insert con;
pagereference p=new pagereference('/'+acc.Id);

pg. 54
return p;
}
}
VF Page:
<apex:page controller="InsertDML1">
<apex:form>
<apex:pageblock >
<apex:commandButton value="save" action="{!create}"/>
<apex:pageblocksection Title="account">
<apex:inputfield value="{!acc.name}"/>
<apex:inputfield value="{!acc.phone}"/>
<apex:inputfield value="{!acc.Industry}"/>
<apex:inputfield value="{!acc.ownership}"/>
<apex:inputfield value="{!acc.rating}"/>
</apex:pageblocksection>

<apex:pageblocksection Title="Contact">
<apex:inputfield value="{!con.Lastname}"/>
<apex:inputfield value="{!con.phone}"/>
<apex:inputfield value="{!con.firstname}"/>
<apex:inputfield value="{!con.MobilePhone}"/>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

pg. 55
Example3: create parent child relation in custom object.
Note: assign the master object id to the child object. As below:

Apex Class:
public class CustomInsert {
public Course__c cc {set;get;}
public Branch__c bb {set;get;}

public CustomInsert(){
cc= new Course__C();
bb=new Branch__c();
}

public void create(){


insert bb;
cc.Branch__c=bb.Id;
insert cc;
}
}
VF Page
<apex:page controller="CustomInsert">
<apex:form>
<apex:pageblock>
<apex:commandButton value="create" action="{!create}"/>
<apex:pageBlockSection title="branch">
<apex:inputField value="{!bb.name}"/>
<apex:inputField value="{!bb.Fee__c}"/>
<apex:inputField value="{!bb.Email__c}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Course">
<apex:inputField value="{!cc.name}"/>
<apex:inputField value="{!cc.Age__c}"/>

pg. 56
<apex:inputField value="{!cc.city__c}"/>
</apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

UPDATE:
Example1: update Rating=warm for account records created today.
Apex Class:
public class DMLupdate1 {
public list<account> acc {set;get;}

public DMLupdate1(){
acc=[select name,phone,industry,rating from account where createddate=Today];
}
public void dmlupdate(){
acc=[select name,phone,industry,rating from account where createddate=Today];
for(account a:acc){
a.rating='warm';
}
update acc;
}
}
VF Page
<apex:page controller="DMLupdate1">
<apex:form>
<apex:pageblock>
<apex:commandButton value="update" action="{!dmlupdate}"/>
<apex:pageblocktable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.phone}"/>
<apex:column value="{!a.rating}"/>
<apex:column value="{!a.industry}"/>
</apex:pageblocktable>
</apex:pageblock>
</apex:form>
</apex:page>
Output

pg. 57
Example2: Fetch all the contacts associated with an account and update contacts homephone as
Account phone number.
Apex Class:
public class DMLPCupdate {
public list<account> acc {set;get;}
public list<selectoption> option {set;get;}
public string selected {set;get;}

public DMLPCupdate(){
option=new list<selectoption>();
acc=[select name,phone,(select lastname,HomePhone from contacts) from account];
for(account a:acc){
selectoption s=new selectoption(a.name,a.name);
option.add(s);
}
}
public void change(){
for(account a:acc){
if(a.name==selected){
for(contact c:a.contacts){
c.HomePhone=a.phone;
update c;
}
}
}
}
}
VF Page:
<apex:page controller="DMLPCupdate">
<apex:form>
<apex:commandButton value="update" action="{!change}"/>
<apex:selectlist value="{!selected}" size="1">
<apex:selectoptions value="{!option}" ></apex:selectoptions>
</apex:selectlist>
<apex:pageblock>
<apex:pageblocktable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.phone}"/>
<apex:column headervalue="name" >
<apex:repeat value="{!a.contacts}" var="b">
{!b.lastname}<br/>

pg. 58
</apex:repeat>
</apex:column>
<apex:column headervalue="Phone" >
<apex:repeat value="{!a.contacts}" var="b">
{!b.homephone}<br/>
</apex:repeat>
</apex:column>
</apex:pageblocktable>

</apex:pageblock>
</apex:form>
</apex:page>
Output:

Example3: changing the owner of a opportunity record of a particular account record ,choose the
owner from a picklist.
Apex Class:
public class UpdatePCop {
public list<Account> acc {set;get;}
public list<selectoption> option {set;get;}
public list<selectoption> users {set;get;}
public string selected {set;get;}
public string selected1 {set;get;}
public list<user> u {set;get;}
public UpdatePCop(){
option=new list<selectoption>();
users=new list<selectoption>();
u=[select id,name from user];
for(user u1:u){
selectoption s2=new selectoption(u1.id,u1.id);
users.add(s2);
}
acc=[select name,industry,ownerid,(select name,stagename,ownerid from opportunities)
from Account where industry='Banking'];
for(Account a:acc){
selectoption s=new selectoption(a.name,a.name);
option.add(s);
}
}
public void disp(){
for(Account a:acc){
if(a.name==selected){
for(opportunity o:a.opportunities){
o.ownerid=selected1;
update o;
}
}
}
}

pg. 59
}
VF page:
<apex:page controller="UpdatePCop">
<apex:form>
<apex:commandButton value="change" action="{!disp}"/>
<apex:selectList size="1" value="{!selected}">
<apex:selectOptions value="{!option}"></apex:selectOptions>
</apex:selectList>
<apex:selectList size="1" value="{!selected1}">
<apex:selectOptions value="{!users}"></apex:selectOptions>
</apex:selectList>
<apex:pageBlock>
<apex:pageBlockTable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.ownerid}"/>
<apex:column value="{!a.Industry}"/>
<apex:column headerValue="name">
<apex:repeat value="{!a.opportunities}" var="b">
{!b.name}<br/>
</apex:repeat>
</apex:column>
<apex:column headerValue="owner">
<apex:repeat value="{!a.opportunities}" var="b">
{!b.ownerid}<br/>
</apex:repeat>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

Delete
Example1: Delete accounts who’s Industry is Education and Rating is HOT.
Apex Class:
public class DMLdel {
public list<account> acc {set;get;}
public list<account> del1 {set;get;}

public DMLdel(){
del1=new list<account>();
acc=[select name,phone,industry,rating from account where Industry='education'];
}
public void del(){
for(account a:acc){

pg. 60
if(a.rating=='Hot'){
del1.add(a);
delete a;
}
}
}
}
VF Page:
<apex:page controller="DMLdel">
<apex:form>
<apex:commandButton value="del" action="{!del}"/>
<apex:pageblock>
<apex:pageblocktable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.phone}"/>
<apex:column value="{!a.industry}"/>
<apex:column value="{!a.rating}"/>
</apex:pageblocktable>
</apex:pageblock>
</apex:form>
</apex:page>
Output: (Higlighted records deleted after pressing del button)

Example2: Transfer child contact of a selected account to another account and delete the account.
Apex class:
public class DMLPCdel {
public list<account> acc {set;get;}
public list<selectoption> option {set;get;}
public string selected {set;get;}
public string selected1 {set;get;}
public id x {set;get;}

public DMLPCdel(){
option=new list<selectoption>();
acc=[select name,phone,ID,(select lastname,firstname,ID from contacts) from account];

for(Account a:acc){
selectoption s=new selectoption(a.name,a.name);
option.add(s);
}
}
public void del(){
for(Account b:acc){
if(b.name==selected1){
x=b.id;
}
}

pg. 61
for(account a:acc){
if(a.name==selected){
for(contact c:a.contacts){
c.accountid=x;
update c;
}
delete a;
}
}
}
}
VF Page
<apex:page controller="DMLPCdel">

<apex:form >
<apex:commandButton value="del" action="{!del}"/>
<apex:pageblock title="To be deleted">
<apex:selectList size="1" value="{!selected}">
<apex:selectOptions value="{!option}"></apex:selectOptions>
</apex:selectList>
</apex:pageblock>
<apex:pageblock title="To be Assigned">
<apex:selectList size="1" value="{!selected1}">
<apex:selectOptions value="{!option}"></apex:selectOptions>
</apex:selectList>

</apex:pageblock>
</apex:form>
</apex:page>
Output:

Undelete
Example1: Undeleting account records from recycle bin.
Apex Class:
public class DMLundel {

pg. 62
public list<account> acc {set;get;}
public list<account> del {set;get;}

public DMLundel(){
acc=[select name,id,phone,industry from account WHERE IsDeleted = true ALL ROWS];
}
public void undel(){
for(account a:acc){
undelete a;
}
}
}
VF Page
<apex:page controller="DMLundel">
deleted rec {!acc}
<apex:form>
<apex:commandButton value="undel" action="{!undel}"/>
</apex:form>
</apex:page>
Output

Example:insert,update,delete,edit,save in one program


Apex Class:
public class AccWrapper {
public account acc {set;get;}
public boolean flag {set;get;}
}
______________________________________________________-
public class Wrapperacc {
public list<AccWrapper> awl {set;get;}
public AccWrapper aw {set;get;}
public list<account> accs {set;get;}
public string name1 {set;get;}
public string industry1 {set;get;}
public integer c {set;get;}

public Wrapperacc() {
awl=new list<AccWrapper>();
accs=[select name,industry,rating from account where rating='Hot'];

for(integer i=0;i<accs.size();i++) {
aw=new AccWrapper();
aw.acc=new Account();
aw.acc=accs[i];
aw.flag=False;
awl.add(aw);
}
}

pg. 63
public void add(){
account a=new account();
a.name=name1;
a.industry=industry1;
a.rating='Hot';
insert a;
}
public void edit(){
for(integer i=0;i<awl.size();i++ ){
if(awl[i].flag==true){
name1=awl[i].acc.name;
industry1=awl[i].acc.industry;
c=i;
}
}
}
public void save(){

awl[c].acc.name= name1;
awl[c].acc.industry=industry1;
update awl[c].acc;
}
public void del(){
list<account> temp=new list<account>();
for(integer i=0;i<awl.size();i++ ){
if(awl[i].flag==true){
temp.add(awl[i].acc);

}
}
delete temp;
}

}
VF Page:
<apex:page controller="Wrapperacc">
<apex:form >
<apex:pageblock Title="actions" >
Name <apex:inputtext value="{!name1}"/><br/>
Industry<apex:inputtext value="{!industry1}"/><br/>
<apex:commandButton value="ADD" action="{!add}" />
<apex:commandButton value="Edit" action="{!edit}" />
<apex:commandButton value="save" action="{!save}" />
<apex:commandButton value="delete" action="{!del}" />
</apex:pageblock>
<apex:pageblock >
<apex:pageblocktable value="{!awl}" var="x">
<apex:column >
<apex:inputcheckbox value="{!x.flag}"/>
</apex:column>

pg. 64
<apex:column value="{!x.acc.name}"></apex:column>
<apex:column value="{!x.acc.rating}"></apex:column>
<apex:column value="{!x.acc.industry}"></apex:column>
</apex:pageblocktable>
</apex:pageblock>
</apex:form>
</apex:page>
Output:

TRY CATCH and SetSavePoint and RollBack.


Apex Class:
public class tc {
public integer count {set;get;}
public integer count1 {set;get;}
public integer count2 {set;get;}
public integer count3 {set;get;}
public list<account> acc {set;get;}

public void tc(){


savepoint sp=Database.setsavepoint();
try{
acc=[select name from account];
count=acc.size();

account a=new Account();


a.name='Australia';
contact c=new contact();
c.LastName='trump';
c.AccountId=a.id;
insert a;
account a1=new Account();
a1.phone='canada';
contact c1=new contact();
c1.firstname='ravi';
c1.AccountId=a.id;
insert a1;
acc=[select name from account];
count1=acc.size();
}catch(exception e){

pg. 65
acc=[select name from account];
count2=acc.size();
Database.rollback(sp);
acc=[select name from account];
count3=acc.size();

}
}
VF Page:
<apex:page controller="tc" >
Before starting try {!count}<br/>
After inserting the faulty record {!count1}<br/>
Before rollback {!count2}<br/>
After rollback {!count3}<br/>
<apex:form>
<apex:commandButton value="sp" action="{!tc}"/>
</apex:form>
</apex:page>
Output:

o
Note:after insert the faulty record is blank because the erlier step (insert)raised an exception
hence this statement is skipped

NON ATOMIC DML:

Insert/update (Non-atomic)
Database.saveresult : This class contains result of an insert or update DML operation and
returned by a database method.
Methods: Issuccess(), getid(), geterrors().
Database.Error: This class represents information about an error, that occurred during DML
operation
Methods: getfields(), getmessage(), getstatuscode();
Example1: inserting the records in non atomic mode and finding the ids of successful records and
Errors.
Apex Code:
public class insertNA {
public list<account> accs {set;get;}
public list<id> ids {Set;get;}

public insertNA(){
ids=new list<id>();

pg. 66
accs= new list<account>();
account a=new account();
a.name='shiva';
a.phone='11111';
accs.add(a);
account b=new account();
// b.name='Parvathi';
b.phone='9999';
accs.add(b);
}
public void ins(){
database.SaveResult[] ds= Database.insert(accs,false);

for(database.saveresult sr:ds){
if(sr.issuccess()){
ids.add(sr.getid());
}
else {
database.error[] de=sr.getErrors();
for(database.error ed:de){

apexpages.message msg=new
apexpages.message(apexpages.Severity.ERROR,'Message'+ed.getmessage());
apexpages.addMessage(msg);

apexpages.message msg1=new
apexpages.message(apexpages.Severity.ERROR,'Code'+ed.getstatuscode());
apexpages.addMessage(msg1);

apexpages.message msg2=new apexpages.message(apexpages.Severity.ERROR,'Error


Fields'+ed.getfields());
apexpages.addMessage(msg2);
}
}
}
}
}
VF Page:
<apex:page controller="insertNA">
success:{!ids}<br/>
<apex:form>
<apex:messages />
<apex:commandButton value="run" action="{!ins}"/>
</apex:form>
</apex:page>
Output:

pg. 67
Example2: Update an existing record using non atomic DML and get the record ids and Error.
Apex Class:
public class updateNA {
public list<account> accs {set;get;}
public list<id> ids {Set;get;}

public updateNA(){
ids=new list<id>();

accs=[select name,phone from account where name='shiva123'];


for(account a:accs){
// a.name=''; if you want to see error msg then remove the comment
a.phone='1234';
}
}
public void ins(){
database.SaveResult[] ds= Database.update(accs,false);

for(database.saveresult sr:ds){
if(sr.issuccess()){
ids.add(sr.getid());
}
else {
database.error[] de=sr.getErrors();
for(database.error ed:de){

apexpages.message msg=new
apexpages.message(apexpages.Severity.ERROR,'Message'+ed.getmessage());
apexpages.addMessage(msg);

apexpages.message msg1=new
apexpages.message(apexpages.Severity.ERROR,'Code'+ed.getstatuscode());
apexpages.addMessage(msg1);

apexpages.message msg2=new apexpages.message(apexpages.Severity.ERROR,'Error


Fields'+ed.getfields());
apexpages.addMessage(msg2);
}
}
}
}
}
VF Page

pg. 68
<apex:page controller="updateNA">
success:{!ids}<br/>
<apex:form >
<apex:messages />
<apex:commandButton value="run" action="{!ins}"/>
</apex:form>
</apex:page>
Output:
Success msg:

Error msg:

Delete (Non-atomic)
Example:Delete specified records from database using NON-Atomic DML
Apex Class:
public class updateNA {
public list<account> accs {set;get;}
public list<id> ids {Set;get;}

public updateNA(){
ids=new list<id>();

accs=[select name,phone from account where name='shiva123'];

}
public void ins(){
database.DeleteResult[] ds= Database.delete(accs,false);

for(database.deleteresult sr:ds){
if(sr.issuccess()){
ids.add(sr.getid());
}
else {
database.error[] de=sr.getErrors();
for(database.error ed:de){

apexpages.message msg=new
apexpages.message(apexpages.Severity.ERROR,'Message'+ed.getmessage());
apexpages.addMessage(msg);

apexpages.message msg1=new
apexpages.message(apexpages.Severity.ERROR,'Code'+ed.getstatuscode());
apexpages.addMessage(msg1);

pg. 69
apexpages.message msg2=new apexpages.message(apexpages.Severity.ERROR,'Error
Fields'+ed.getfields());
apexpages.addMessage(msg2);
}
}
}
}
}
VF Page:
<apex:page controller="updateNA">
success:{!ids}<br/>
<apex:form >
<apex:messages />
<apex:commandButton value="run" action="{!ins}"/>
</apex:form>
</apex:page>
Output:

UPSERT(NON-ATOMIC)
Example:performing non atomic upsert
Apex Class:
public class upsertNA {
public list<account> accs {set;get;}
public list<id> ids {Set;get;}

public upsertNA(){
ids=new list<id>();
accs= [select id,name,industry,phone from account limit 10];
for(account z: accs){
if(z.industry=='banking'){
z.ownership='Public';
}
}
account a=new account();
a.name='hari';
a.phone='11111';
accs.add(a);

}
public void ins(){
database.UpsertResult[] ds= Database.upsert(accs,false);

for(database.upsertresult sr:ds){
if(sr.issuccess()){

pg. 70
ids.add(sr.getid());
}
else {
database.error[] de=sr.getErrors();
for(database.error ed:de){

apexpages.message msg=new
apexpages.message(apexpages.Severity.ERROR,'Message'+ed.getmessage());
apexpages.addMessage(msg);

apexpages.message msg1=new
apexpages.message(apexpages.Severity.ERROR,'Code'+ed.getstatuscode());
apexpages.addMessage(msg1);

apexpages.message msg2=new apexpages.message(apexpages.Severity.ERROR,'Error


Fields'+ed.getfields());
apexpages.addMessage(msg2);
}
}
}
}
}
VF Page:
<apex:page controller="upsertNA">
success:{!ids}<br/>
<apex:form >
<apex:messages />
<apex:commandButton value="run" action="{!ins}"/>
</apex:form>
</apex:page>
Output:

UNDELETE(NON-ATOMIC)
Example:performing non atomic undelete
Apex Class:
public class undelNA {
public list<account> accs {set;get;}
public list<id> ids {Set;get;}

public undelNA(){
ids=new list<id>();
accs=[select name from Account where isdeleted=true ALL ROWS];
}
public void ins(){
database.UndeleteResult[] ds= Database.undelete(accs,false);

for(database.undeleteresult sr:ds){
if(sr.issuccess()){
ids.add(sr.getid());

pg. 71
}
else {
database.error[] de=sr.getErrors();
for(database.error ed:de){

apexpages.message msg=new
apexpages.message(apexpages.Severity.ERROR,'Message'+ed.getmessage());
apexpages.addMessage(msg);

apexpages.message msg1=new
apexpages.message(apexpages.Severity.ERROR,'Code'+ed.getstatuscode());
apexpages.addMessage(msg1);

apexpages.message msg2=new apexpages.message(apexpages.Severity.ERROR,'Error


Fields'+ed.getfields());
apexpages.addMessage(msg2);
}
}
}
}
}
VF Page:
<apex:page controller="undelNA">
success:{!ids}<br/>
<apex:form >
<apex:messages />
<apex:commandButton value="run" action="{!ins}"/>
</apex:form>
</apex:page>
Output:

DELETE RECYCLEBIN(NON_ATOMIC)
Example:performing non atomic delete recyclebin
Apex Class:
public class undelNA {
public list<account> accs {set;get;}
public list<id> ids {Set;get;}
public undelNA(){
ids=new list<id>();
accs=[select name from Account where isdeleted=true ALL ROWS];
}
public void ins(){
database.emptyrecyclebinresult[] ds= Database.emptyrecyclebin(accs);
for(database.emptyrecyclebinresult sr:ds){
if(sr.issuccess()){

pg. 72
ids.add(sr.getid());
}
else {
database.error[] de=sr.getErrors();
for(database.error ed:de){

apexpages.message msg=new
apexpages.message(apexpages.Severity.ERROR,'Message'+ed.getmessage());
apexpages.addMessage(msg);

apexpages.message msg1=new
apexpages.message(apexpages.Severity.ERROR,'Code'+ed.getstatuscode());
apexpages.addMessage(msg1);

apexpages.message msg2=new apexpages.message(apexpages.Severity.ERROR,'Error


Fields'+ed.getfields());
apexpages.addMessage(msg2);
}
}
}
}
}
VF Page:
<apex:page controller="undelNA">
success:{!ids}<br/>
<apex:form >
<apex:messages />
<apex:commandButton value="run" action="{!ins}"/>
</apex:form>
</apex:page>
Output:

TRIGGERS
Triggers are the automated actions which are performed whenever a DML operations are
performed on the object.

pg. 73
Trigger Type:
1. Before Trigger: These triggers are fired before the new data is saved to the database.
2. After Trigger: These triggers are fired after the data is saved to the database.
Trigger Events: These are the events that will fire the triggers when DML is performed.
1. Before Insert
2. After Insert
3. Before update
4. After update
5. Before Delete
6. After Delete
7. After Undelte

pg. 74
Trigger Context Variables:
There variables are used to hold data required during the runtime of the operation.

IsInsert : This will return true if the trigger is fired due to DML operation of insert.
IsUpdate : This will return true if the trigger is fired due to DML operation of update.
IsDelete : This will return true if the trigger is fired due to DML operation of delete.
IsUndelete : This will return true if the trigger is fired due to DML operation of undelete.

IsBefore: This will return true if the trigger is fired due to before event.
IsAfter: This will return true if the trigger is fired due to after event.

New: This will return list of new version of records on which DML is performed.
NewMap: This will return map of new version of records with record id as key and record as value.

Old: This will return list of old version of records on which DML is performed.
OldMap: This will return map of old version of records with record id as key and record as value.

Syntax:
Trigger Triggername on subject(trigger events) {
}

pg. 75
pg. 76
pg. 77
INSERT TRIGGER:
Before Insert:
1. Trigger.new: The list of new records which are trying to insert are stored in Trigger.new
2. In the before insert new records which we are tying to insert cannot be fetched using
SOQL.
3. If you want to modify the records which are in trigger.new, we can perform Write
operation.
4. If you want to create child record object then use AFTER INSERT (by Ravi Teja said:
because without ID we cannot assign the child record to parent.)
Example1: Whenever new account is created with industry as banking then set ownership as
private.
Apex Trigger:
trigger IT1 on Account (before insert) {
for(account a:trigger.new){
if(a.industry=='Banking'){
a.ownership='Private';
}
}
}
Output:

Example2: Whenever new Account is created with Industry as EDUCATION and RATING as Warm.
Then create new opportunity with Opportunity name as account name and other details.
Apex Trigger
trigger IT_accopty on Account (before insert) {
list<opportunity> opty=new list<opportunity>();
for(account a:trigger.new){
if(a.Industry=='Education' && a.Rating=='Warm'){
opportunity op=new opportunity();
op.name=a.name;

pg. 78
op.Type='New Customer';
op.CloseDate=system.today()+15;
op.StageName='Prospecting';
opty.add(op);
}
}
insert opty;
}
Output:

Example3: When a new Contact is inserted with out Account then throw error message
Apex Trigger:
trigger IT_contact on Contact (before insert) {
for(contact c:trigger.new){
if(c.Account==null){
c.addError('Enter account name');
}
}
}
Output:

Example3: When a new Account is inserted with Industry as banking assign the owner as
'Ramana p'
Ramana should have salesforce licence.
Apex Trigger:
trigger IT_accAssign on Account (before insert) {
user u=[select name from user where alias='rpa' limit 1];

for(account a:trigger.new){
if(a.industry=='Banking'){
a.ownerid=u.id;
}
}
}
Output:

pg. 79
After Insert:
1. Trigger.new: The list of new records which are SUCCESSFULLY SAVED to the sobject are in
Trigger.new
2. In the after insert new records which are in trigger.new can be fetched using SOQL.
If you want to modify the records which are in trigger.new, we can perform DML operation.
Example1: Whenever new Account is created with Industry as EDUCATION and RATING as Warm.
Then create new CHILD opportunity with Opportunity name as account name and other details to
account
Apex Trigger:
trigger IT_accopty on Account (before insert) {
list<opportunity> opty=new list<opportunity>();
for(account a:trigger.new){
if(a.Industry=='Education' && a.Rating=='Warm'){
opportunity op=new opportunity();
op.name=a.name;
op.Type='New Customer';
op.CloseDate=system.today()+15;
op.StageName='Prospecting';
op.AccountId=a.Id;
opty.add(op);
}
}
insert opty;
}
Output:

pg. 80
Example2:when ever new account is created with annual revenue more thhan 5lak then add
“Ramana P” as a AccountTeamMember
Apex Trigger:
trigger IT_atm on Account (after insert) {
list<AccountTeamMember> atm1=new list<AccountTeamMember>();
user u=[select name from user where alias='rpa'];
for(account a:trigger.new){
if(a.AnnualRevenue>500000){
AccountTeamMember atm=new AccountTeamMember();
atm.userid=u.id;
atm.AccountId=a.id;
atm.TeamMemberRole='Lead Qualifier';
atm.AccountAccessLevel='All';
atm1.add(atm);
}
}
insert atm1;
}
Output:

Example3: when ever new account is created with annual revenue more thhan 5lak then add
“Ramana P” as a AccountTeamMember along with change the account owner as “Ramana p”
Apex Class:
trigger IT_atm on Account (after insert) {
list<AccountTeamMember> atm1=new list<AccountTeamMember>();
user u=[select name from user where alias='rpa'];
for(account a:trigger.new){
if(a.AnnualRevenue>500000){
AccountTeamMember atm=new AccountTeamMember();

pg. 81
atm.userid=u.id;
atm.AccountId=a.id;
atm.TeamMemberRole='Lead Qualifier';
atm.AccountAccessLevel='All';
atm1.add(atm);
}
list<account> acc=new list<account>();
acc=[select name,id from account where id in:trigger.new];
for(account b:acc){
b.ownerid=u.id;
update b;
}
}
insert atm1;
}
Output:

Example 4: When ever a new contact is created submit the record for approval to ‘Ramana P’
Note: Before writing the code approval process to be created in admin.
Trigger class:
trigger appcontact on Contact (after insert) {
for(contact c:trigger.new){
if(c.LeadSource=='web'){//if you want to do this in admin also
approval.ProcessSubmitRequest req1=new approval.ProcessSubmitRequest();
req1.setProcessDefinitionNameorId('Web contact approval');// you can pass name or Id
req1.setobjectid(c.id);
user u=[select id from user where alias='rpa'];
req1.setsubmitterid(userinfo.getUserId());
id[] ids=new id[]{u.id};
req1.setNextApproverIds(ids);
// req1.setskipentrycriteria(true); If you want to skip the entry condition in admin approval
step
approval.ProcessResult result=approval.process(req1);
}
}

pg. 82
}
Approval Process:

Output:

Example 5: When a new contact is created for an existing account then set contact of the
otherphone as account phone.
Apex Trigger:
trigger cont_acc on Contact (after insert) {
list<account> acc =[select name,phone,id,(select id,otherphone,accountid from contacts where id
in:trigger.new) from account];
for(Account a:acc){
for(contact c:a.contacts){
if(c.accountid==a.id){
c.OtherPhone=a.phone;
update c;
}
}

pg. 83
}
}
Output:

TASK

Example6: When a new Account is created with Account Type as prospect then Create new Task
for the ‘’Ramana P” of the record .
Apex Trigger:
trigger acctri1 on Account (after insert) {
user u=[select name from user where alias='rpa'];
list<task> t1=new list<task>();
for(account a:trigger.new){
if(a.Type=='prospect'){
task t=new task();
t.whatid=a.id;
t.Priority='normal';
t.Status='not started';
t.OwnerId=u.Id; //if u want assign to owner t.ownerid=a.id
t1.add(t);

pg. 84
}
}
insert t1;
}
Output:

Example7: When a new Account is created with Account Type as prospect then Create new Task
for the “Ramana P” of the record and send email alert to the “Ramana P”.
Apex Trigger:
trigger acctri1 on Account (after insert) {
user u=[select name,email from user where alias='rpa'];
list<task> t1=new list<task>();
for(account a:trigger.new){
if(a.Type=='prospect'){
task t=new task();
t.whatid=a.id;
t.Priority='normal';
t.Status='not started';
t.subject='cal to him with in 7 days';
t.OwnerId=u.Id;
t1.add(t);
Messaging.SingleEmailMessage msg=new Messaging.SingleEmailMessage();
string[] cc=new string[]{u.Email};
msg.setToAddresses(cc);
/*string[] cc1=new string[]{'bvipin.2000@gmail.com'};//if u want to send other emails use
this "setccaddresses"
msg.setccAddresses(cc1);*/
string body='dear customer';
msg.setplaintextbody(body);
msg.setsubject('teat email');
Messaging.Email[] emails=new Messaging.Email[]{msg};
Messaging.sendEmail(emails);
}
}
insert t1;
}
Output:
Note:Task created and Email send to specified email id
Example8:when ever new lead is created then send a mail to customer and owner.
Apex Trigger:
trigger Leadmsg on Lead (after insert) {
for(Lead lee:trigger.new){
Messaging.SingleEmailMessage msg=new Messaging.SingleEmailMessage();
string mail=userinfo.getUserEmail();
string[] options=new string[]{mail,lee.Email};
msg.SetToAddresses(options);//we can not use more than one "setToAddresses"
string body='dear customer';
msg.setplaintextbody(body);

pg. 85
msg.setsubject('teat email');
Messaging.Email[] emails=new Messaging.Email[]{msg};
Messaging.sendEmail(emails);

}
}
Output:
Email was sent to customer and owner

BEFORE UPDATE

Example1:when ever industry is chaging to banking update phone


Apex Trigger:
trigger BefUp on Lead (before update) {
for(lead l:trigger.new){
if(l.Industry=='banking'){
l.Phone='8978130541';
}
}
}
Output:

pg. 86
Example2:when ever industry is changed to banking make “ramana P” as owner and send task and
Email to “ramana P”.
Apex Trigger:
trigger BefUp on Lead (before update) {
user u=[select name,Email from user where alias='rpa'];
list<task> t1=new list<task>();
for(lead l:trigger.new){
if(l.Industry=='banking'){
l.Phone='8978130541';
l.OwnerId=u.id;
}
task t=new task();
t.subject='Take care of sfdc';
t.OwnerId=u.id;
t.WhoId=l.id;
t.Priority='normal';
t.Status='not-started';
// t1.add(t);
insert t;
messaging.SingleEmailMessage msg=new messaging.SingleEmailMessage();
string[] email=new string[]{u.Email,l.Email};
msg.setToAddresses(email);
string body='dear customer';
msg.setplaintextbody(body);
msg.setsubject('Take care of sfdc');
Messaging.Email[] emails=new Messaging.Email[]{msg};
Messaging.sendEmail(emails);

}
}
Output:

Emails also sent

pg. 87
Example2:when ever account ownership is changed from public to private update a phone.
Apex Trigger:
trigger UpDaBef on Account (before update) {
map<id,Account> oldmap=trigger.oldMap;
map<id,Account> newmap=trigger.newMap;
for(id key:newmap.keySet()){
Account ol=oldmap.get(key);
account nw=newMap.get(key);
if(ol.ownership=='public' && nw.Ownership=='private'){
nw.Phone='765536374646';
}
}
}
Output:phone updated only when ownership is changed public to private.

pg. 88
AFTER UPDATE

pg. 89
Example1:when ever the opportunity stagename is modified to closed Won and amount is more
than 1000 then share the record to” ramana P”.(calling apex class from trigger)
 .Before doing this,go to sharing settings and select opportunity object as private.
 .remove modify all permission in opportunity object of ramana profile.

pg. 90
Apex Class:
public class owdtRI {
public static void afterupdate(map<id,opportunity> oldmap,map<id,opportunity> newmap){
list<opportunityShare> share=new list<opportunityShare>();
user u=[select name from user where alias='rpa'];
for(id key:oldmap.keyset())
{
opportunity old=oldmap.get(key) ;
opportunity newmap1=newmap.get(key) ;

pg. 91
if(old.StageName!='Closed Won' && newmap1.StageName=='Closed Won'){
if(newmap1.Amount>1000){
opportunityShare os=new opportunityShare();
os.OpportunityId=key;
os.UserOrGroupId=u.id;
os.OpportunityAccessLevel='Read';
os.RowCause='manual';
share.add(os);
}
}
}
insert share;
}
}
Apex trigger:
trigger Sharetrigger on Opportunity (after update) {
owdtRI.afterupdate(trigger.oldmap,trigger.newmap);
}
Output:

Example2:When ever an account phone is modify update all the contacts of the account
 .contacts other phone as oldphine of account
 .contacts mobile phone as newphone of account
Apex Trigger:
trigger pctrigger on Account (after update) {
list<account> acc=[select name,phone,(select name,otherphone,mobilephone from
contacts)from account];
map<id,Account> oldmap1=trigger.oldmap;
map<id,Account> newmap1=trigger.newmap;
for(id key:oldmap1.keyset()){
account ol=oldmap1.get(key);
account nu=newmap1.get(key);
if(ol.phone!=nu.phone){
for(account a:acc){
for(contact c:a.contacts){
c.OtherPhone=ol.phone;
c.MobilePhone=nu.phone;
update c;
}

pg. 92
}
}
}
}
Output:

Delete

Before Delete:
Example1:If you delete any account record corresponding child contact records to be assigned to a
particular account(Salman).
Apex Trigger:
trigger accdeltri on Account (before delete) {
list<account> acc=[select name,id,(select lastname,id,accountid from contacts)from account
where id in:trigger.old];
account a1=[select name,id from account where name='salman'];
for(account a:acc){
for(contact c:a.contacts){
c.AccountId=a1.id;
update c;
}
}
}
Output:

pg. 93
AFTER DELETE
Example1:Delete the account when there are no contacts available in Account.This should trigger
when you delete the last contact of an account.
Apex Trigger:
trigger delacctri on Contact (after delete) {
list<id> ids=new list<id>();
for(contact c:trigger.old){
if(c.AccountId!=null){
ids.add(c.AccountId);
list<contact> con=[select lastname,accountid,id from contact where accountid in:ids];
if(con.size()==0){
account a=[select name,id from account where id in:ids];
delete a;
}
}
}
}
Output:Account was deleted

After deleting four contact records then only account record deleted.

pg. 94
UNDELETE(After Undelete)

Example:when ever undelete the account records from recyclebin update the active field as “yes”.
Apex Trigger:
trigger undeletetri on Account (after undelete) {
list<account> acc=[select name,id from account where id in:trigger.new ];
for(account a:acc){
a.Active__c='yes';
update a;
}
}
Output:

pg. 95
Email Services
Outbound Email Services : If you are sending an email from salesforce to external system.
Single Email Services:
Example 1: Sending emails to the contacts which are created today. Which includes Sending plain
body, HTML body, HTML Template, and sending attachments.
 Email template can send only to Lead,Contact,User without email template wecan send to
every object and others.
Apex Class: This can be run from anonymous window
public class EmailAlert {
/*--------------------------------------------------------------------------------------*/
public void EmailPlainBody(){
list<contact> con1=[select name,Email,Id from contact where createddate=TODAY];

for(contact c1:con1){
messaging.SingleEmailMessage msg=new messaging.SingleEmailMessage();
string[] email=new string[]{c1.Email};
msg.setToAddresses(email);
msg.setsubject('name is '+c1.name);
msg.setplaintextbody('This is body of'+c1.name);
messaging.Email[] sm =new messaging.email[]{msg};
messaging.sendEmail(sm);
}
}
/*--------------------------------------------------------------------------------------*/
public void EmailHtmlBody(){
list<contact> con1=[select name,Email,Id from contact where createddate=TODAY];
for(contact c1:con1){
messaging.SingleEmailMessage msg=new messaging.SingleEmailMessage();
string[] email=new string[]{c1.Email};
msg.setToAddresses(email);
msg.setsubject('name is '+c1.name);
string body='<H1> Dear customer,<br/></H1><H2> We have recieved your
payment</H2><br/><H3> Thankyou</H3>';
Body=body+'<H1><Font style="color:Red"> Welcome you </Font></H1>';
msg.sethtmlbody(body);
messaging.Email[] sm =new messaging.email[]{msg};
messaging.sendEmail(sm);
}
}
/*--------------------------------------------------------------------------------------*/
public void EmailHtmlTemplate(){ //Email template can be sent to only Lead,Contact and User
list<contact> con1=[select name,Email,Id from contact where createddate=TODAY];
for(contact c1:con1){
messaging.SingleEmailMessage msg=new messaging.SingleEmailMessage();
emailtemplate et=[select id from emailtemplate where name='ContactAlert'];
msg.settargetobjectid(c1.id);
msg.settemplateid(et.Id);
messaging.Email[] sm =new messaging.email[]{msg};
messaging.sendEmail(sm);

pg. 96
}
}

/*--------------------------------------------------------------------------------------*/
public void EmailAttachment(){
list<contact> con1=[select name,Email,Id from contact where createddate=TODAY];
list<messaging.EmailFileAttachment> at2=new list<messaging.EmailFileAttachment>();

for(contact c1:con1){
at2.clear();
messaging.SingleEmailMessage msg=new messaging.SingleEmailMessage();
document d=[select name,id,body from document where name='attachment'];
messaging.EmailFileAttachment at1=new messaging.EmailFileAttachment();
at1.setfilename(d.name);
at1.setbody(d.Body);
at2.add(at1);
msg.setfileattachments(at2);
string[] email=new string[]{c1.email};
msg.setToaddresses(email);
string body='<H1> Dear customer,<br/></H1><H2> We have recieved your
payment</H2><br/><H3> Thankyou</H3>';
Body=body+'<H1><Font style="color:Red"> Welcome you </Font></H1>';
msg.sethtmlbody(body);
msg.setplaintextbody('this is plain text'+c1.name); //This will not be considered as it will take
Html page
msg.setsubject('This mail is for :'+c1.name);
messaging.Email[] sm =new messaging.email[]{msg};
messaging.sendEmail(sm);
}
}
}
Output:
Plain Text:

HTML body:

HTML Template

pg. 97
Attachment

Example2:sending emails based on email field of account object.


Apex Class:
public class Massemail {
public void massplaintext(){
list<account> acc = [select id,name,Email__c from account where createddate=TODAY];
for(Account c:acc){
if(c.email__c!=null && c.email__c!=''){
string[] emails=new string[]{c.email__c};
messaging.singleEmailMessage msg=new messaging.singleEmailMessage();
msg.settoaddresses(emails);
msg.setsubject('This is vipin bro doubt');
msg.setplaintextbody('ravi is doing everything');
messaging.email[] email= new messaging.email[]{msg};
messaging.sendEmail(email);
}
}
}
}
Output:

pg. 98
Mass Email Services
Example1: Sending Mass Email to contact object using HTML template
Apex Class: This can be run from anonymous window
public class Massemail {
public void massplaintext(){
list<contact> con = [select name,id,email from contact where createddate=TODAY];
list<id> ids=new list<id>();
for(contact c:con){
ids.add(c.id);
}
messaging.MassEmailMessage msg=new messaging.MassEmailMessage();
msg.settargetobjectids(ids);
emailtemplate et=[select id from emailtemplate where name='ContactAlert'];
msg.settemplateid(et.id);
// msg.setsubject('This is subject'); Template contains subject.
messaging.email[] email= new messaging.email[]{msg};
messaging.sendEmail(email);
}
}
Output:

pg. 99
INBOUND EMAIL SERVICES: : If you are receiving an email from external system to salesforce .

pg. 100
pg. 101
Example:when ever email received from external system to salesforce then create a new account
with email details.
Apex Class:This class runs when ever email received to the corresponding email generated by
emai services for this class.
global class helloguru1 implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail
email, Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
string aname=email.fromname;
string des=email.subject;
string indu=email.fromAddress;
account a=new account();
a.name=aname;
a.Description=des;
a.Industry=indu;
a.Email__c='ravu@gmail.com';
insert a;
return result;
}
}
Output:

ASYNCHRONOUS OPERATIONS:
Synchronous:in a synchronous call,the thread will wait until it completes its tasks before
procceding to next. And the code runs in a single thread.
Asynchronous: in a asynchronous call,the thread will NOT wait until it completes its tasks before
procceding to next. And the code runs in a multiple thread.Which helps to do many tasks.
Types of Asynchronous Operations:
1. Future Methods
2. Queueable Apex
3. Batch Apex
4. Schedule Apex

Future Method
If a Transaction has any long running operations/statements, and if this operation is not having
any dependency on rest of the operations. Then we can run the operation independently from the
rest of the operation by using future method.
Example: Long running operations can be webservice call, bulk DML Operations,

pg. 102
Rules to define future method:
1. All the future methods should have “@future” annotation.
2. All the future methods should be defined as static.
3. All the future method should have void as return type
4. Only premetive variables can be passed as parameters.
5. When we call the future method they will be added in Queue and from Queue they will be
executed.
6. If you want to invoke webservices from the future method then define
@future(callout=true)
7. Any asynchronous job that is running in salesforce will be registered with AsyncApexJob
Object.
8. How to track the status of future method?
o Write a SOQL query on AsyncApexJob.
o Declarative way to check the status.
Setup -> Monitor-> Jobs->Apex Jobs
9. Future methods can be used to increase the Governing Limits
@future(limits=dml*2)

Example1: calling Future method and an apex method combindly from a single method.
Apex Class:
public class FutureAcc {

public void acc(){


List<Account> acc=[select id,Email__c,fax,phone from Account where industry='banking'];
for(account a:acc){
a.phone='+9999999';
a.Email__c='vipin@gmail.com';
update a;
}
}
@future
public static void accs(){
List<Account> acc=[select id,Email__c,fax,phone from Account where industry='banking'];
for(account a:acc){
a.fax='+911111111';
a.Email__c='raju@gmail.com';
update a;
}
}
public void accss(){
acc();
accs();
}
}
Output: First Future method executed and then the normal method

pg. 103
Example 2: Passing IDs to the apex method and Future method for execution.
Apex Class:
public class FutureId {
public list<id> ids;
public FutureId(){
ids=new list<id>();
List<account> acc=new list<account>();
acc=[select id from Account where industry='banking'];
for(account a:acc){
ids.add(a.id);
}
}
public void accMethod(list<id> id1){
List<account> acc1=new list<account>();
acc1=[select id,name,phone,fax,Email__c from account where id in:id1];
for(account a:acc1){
a.phone='+5555555555';
a.Email__c='ravi@gmail.com';
update a;
}
}
@future
public static void accFuture(list<id> id3){
List<account> acc2=[select id,name,phone,fax,Email__c from account where id in:id3];
for(account a:acc2){
a.phone='+000000000';
a.Email__c='vipin@gmail.com';
update a;
}
}
public void callboth(){
accMethod(ids);
accFuture(ids);
}
}
Output:

Mixed DML Exception:


If you make a DML operation on setup objects and non-setup objects, in a single transaction then
it thorows Error as “mixed DML Exception”
Setup Objects:
1. User
2. Group
3. Groupmember
4. Permissionset
5. ObjectPermissions

pg. 104
6. UserRole
7. PremissionSetAssigment
8. QueueSObject
9. ObjectTerritory2AssigmentRule
10. ObjectTerritory2AssigmentRuleItem.
11. RuleTerritory2Association
12. SetupEntityAccess
13. Territory2
14. Territory2Model
15. UserTerritory2Association
16. UserTerritory
17. Territory

Non-Setup Objects: Rest of the Objects are Non-setup Objects, Example,


Account,contact,customer__c etc.
Example1: if we use Setup and Non setup operation in a single code we will get DML Exception.The
following code demonstrate and resolve the issue.
Code with mixed setup and non-setup operation
public class mde {
public void create(){
/*------------------Setup operation----------------------*/
profile p=[select id from profile where name='Field Executive'];
userrole u1=[select id from userrole where name='HR_manager'];
user u=new user();
u.alias='kranti';
u.Email='kranti@gmail.com';
u.emailencodingkey='UTF-8';
u.LanguageLocaleKey='en_US';
u.Localesidkey='en_US';
u.ProfileId=p.id;
u.userroleid=u1.id;
u.timezonesidkey='America/Los_Angeles';
u.username='Koteshswamy@gmail.com';
u.lastname='reddy';
insert u;
/*------------------Non-Setup operation----------------------*/
account a=new account();
a.name='silksmita';
a.Email__c='silksmita@gmail.com';
insert a;

}
}
Output:

pg. 105
Solution of the DML Exception:
Put any one of the setup/Non-setup in the future method and call the future method from the
normal method.
Apex code:
public class mde {
public void create(){
/*------------------Setup operation----------------------*/
profile p=[select id from profile where name='Field Executive'];
userrole u1=[select id from userrole where name='HR_manager'];
user u=new user();
u.alias='kranti';
u.Email='kranti@gmail.com';
u.emailencodingkey='UTF-8';
u.LanguageLocaleKey='en_US';
u.Localesidkey='en_US';
u.ProfileId=p.id;
u.userroleid=u1.id;
u.timezonesidkey='America/Los_Angeles';
u.username='Koteshswamy@gmail.com';
u.lastname='reddy';
insert u;
futurecall();
}
/*------------------Non-Setup operation----------------------*/
@future
public static void futurecall(){
account a=new account();
a.name='silksmita';
a.Email__c='silksmita@gmail.com';
insert a;
}
}
Output: Both user and Account created

pg. 106
Drawbacks:
1. Future Method will not return JobId in th apex code.
2. Future method can not be called from another future method.
3. Future method will not support Sobjects as parameters.
Limits:
1. Within the transaction we can call 50 future methods.

pg. 107
QUEUABLE APEX
1. If we want to run apex class asynchronously then we use the concept of queuable apex.
2. These are used to run the long running operations like external webservices call and bulk
database oprations asynchronously.
3. If you want to run apex class as queuable apex then apex class has to implement
“queuable” interface.
4. Any apex class which implements queuable interface has to define “execute” method .
Syntax:public void execute(queuableContext qc){}
5. Business logic which we want to run asynchronous is defined with in the execute method.
6. When we invoke the queuable job using system.enquejob() method ,this will return id of
the asynchronous job.using which we can track the status of the job.
7. Future method will not return id of the job.
8. Using non-Primitive type :Your queuable class can contain member variables of non-
primitive datatypes.
9. Future method will not accept non-primitive datatypes as parameters.
10. Chaining Job:We can invoke queuable apex from other queuable apex.
 We can order the execution of queuable2 from queuable1.
 Note:Future method cannot be call from another future method.
11. How to track the status of future method?
a. Write a SOQL query on AsyncApexJob using the jobid return by
system.enqueuejob().
EX:select id ,name from ayncapexjob where createddate=today
b. Declarative way to check the status.
Setup -> Monitor-> Jobs->Apex Jobs

Example:With Queueable apex update the Account records and assign the jobid to description field of
account.
Apex Class:
public class QueuableExample implements Queueable {
public void execute(QueueableContext qc){
List<Account> acc=[select id,Email__c,fax,phone,description from Account where
industry='banking'];
for(account a:acc){
a.phone='+5555555555';
a.Email__c='garu@gmail.com';
string ids=qc.getJobId();
a.Description=ids;
update a;
}
}
}
Ananomous Window:For Execution
QueuableExample qe=new QueuableExample();
system.enqueueJob(qe);
Output:

pg. 108
Example2: Chaining Apex classes and retrieving ids of the Queueable apex.
Apex Class:
public class chainingApex1 implements Queueable {
public void execute(queueablecontext qc){
list<account> acc1=[select name,phone,industry,fax,description from account where
industry='banking'];
for(account a:acc1){
a.phone='1111111';
id x1=qc.getJobId();
a.description=x1;
update a;
}
}
}
public class ChainingApex2 implements Queueable {
public void execute(queueablecontext qc1){
list<account> acc2=[select name,phone,industry,fax,sic from account where
industry='banking'];
for(account b:acc2){
b.fax='2222222';
id x=qc1.getJobId();
b.Sic=x;
update b;
}
ChainingApex1 ca=new ChainingApex1();
id ids=system.enqueueJob(ca);
}
}
Ananomous window:
ChainingApex2 ca2=new ChainingApex2();
system.enqueueJob(ca2);
Output:

pg. 109
GOVERNING LIMITS:
Salesforce by default on every apex functionality imposed some limits to obey multi-tenant
artitecture.
Governing Limits:
1. In every transaction maximum no. of SOQL statements : 100.
2. In every transaction maximum no. of DML statements : 150.
3. In every transaction maximum no. of Records on which DML can be performed : 10,000.
4. Every SOQL Query can return maximum : 50,000 Records.
5. In every transaction maximum no. of SOSL statements : 20.
6. In every transaction maximum no. of Future Methods : 50.
7. In every transaction maximum no. of Queueable call: 50.
8. In every transaction maximum no. of callouts : 100.
9. In every transaction maximum no. of Email Invocations : 10.
SOQL Governing Limits:
ApexClass:
public class SOQLGovlim {
public void SOQLcall(){
for(integer i=0;i<101;i++){ //it will run if we make i<100
list<account> acc=[select name from account];
}
}
}
Output:

DML Governing Limits:


Apex Class:
public class SOQLGovlim {
public void SOQLcall(){
for(integer i=0;i<151;i++){ // it will work if i<150
account a=new account();
a.name='Gangu singh';
a.Email__c='Gangu@gmail.com';
insert a;
}
}
}

pg. 110
Output:

Maximum no records on which DML can be performed is 10000


Apex Code:
public class SOQLGovlim {
public void SOQLcall(){
list<contact> con=new list<contact>();
for(integer m=0;m<=5000;m++){
contact c=new contact();
c.LastName='GanguG';
con.add(c);
}
insert con;
delete con;
}
}
Output:

BATCH APEX:
1. When you want to process large no of records on daily basis or nightly basis or specific
time of interval, then there is a possibility of encountering the Governing limits.
2. To resolve this governing limit issue, we will run the operation as Asynchronous operation
using batch apex.

pg. 111
3. Batch Apex is exposed as an interface, that must be implemented by the developer. Batch
jobs can be programmatically invoked at runtime using apex.
4. Batch Apex will break the large set of records into no. of batches with small set of data
and every batch will run independent from eachother with fresh set of governing limits.
5. If you want any apex class to run like batch apex, that apex class has to implement an
Interface “Database.Batchable”.
6. Any apex class which implements Database.Batchable interface should define 3 methods
a. Start
b. Execute
c. Finish.
Start Method:
a. This method will be called at the starting of the Batch Job and collects the data on
which the Batch Job need to be operated.
Syntax: Database.Querylocator Iterable <Sobject> Start(Database.Batchablecontext bc){}
b. Database.Querylocator : When you are using a simple query( SELECT…… ) to
generate the scope of records on which batch job should run, use
Database.Querylocator.
c. If you use a Querylocator object, The Governer limit for the total no. of records
retrived by SOQL query is bypassed and we can fetch upto 50 Million records in a
SOQL query.
d. Use the Iterable to create a complex scope for the batch job. You can also use the
Iterable to create your own custom process for iterating through the list.
e. If you are using Iterable, all Governing limits will be still enforced.
f. Start method will break the list of records into no. of batches and invoke the
execute method on every batch.
Execute Method:
a. This method will be invoked by the START Method on every batch of records.
b. This method will containg business logic, That need to performed on the records
fetched from the start method.
Syntax: Global Void Execute(Database.Batchablecontext bc,List<Sobject> scope){}
c. List<Sobject> contains the list of records in the batch job on which this execute
method is running.
d. Example: if Start method fetched 1000 records and devided into 5 batchs with
200 records in each batch, then execute method will be called on every batch
separately (Execute method will be called 5 times)
Finish Method:
a. This method will be called after executing all the execute methods.
b. This method is used to send conformation email post batch operations.
Syntax: Global Void Finish(Database. Batchablecontext bc){}

pg. 112
Limits of Batch Apex:
1. At a time only 5 batch jobs will run.
2. At a time 100 jobs can be added to flexQueue.
3. In a batch Job, if any one of the batch job fails, only that batch will fail and rest of the
batches will execute normally.
4. If the finish method fails, only finish method will fail and changes made by the execute
method will be commited.
5. We cannot call future method from the batch apex.
6. We can call batch jobs from finish method of another batch job.
7. If you want to call webservices from the batch apex, apex class has to implement
“Database.allowcallouts” interface.
Example1:Fetch account records and update some fields and send the email to account holder.
Apex Class:
Global class BatchExample implements Database.Batchable<Sobject>{
Global Database.QueryLocator start(database.BatchableContext bc ){
Return Database.getQueryLocator('Select id,name,phone,Email__c,Description from
account');
}
Global void Execute(Database.BatchableContext bc,List<account> acc){
list<account> bat=new list<account>();
for(account a:acc){
a.phone='0090091';
a.Email__c='ravi@gmail.com';
a.Description=bc.getjobid();
bat.add(a);
}

update bat;
string[] x= new string[]{};
for(account a:bat){
x.add(a.Email__c);
}
messaging.SingleEmailMessage msg=new messaging.SingleEmailMessage();
msg.setToAddresses(x);
msg.setsubject('Batch Execution');
msg.setplaintextbody('batch Execution');
messaging.Email[] em=new messaging.Email[]{msg};
messaging.sendemail(em);
}
Global void Finish(Database.Batchablecontext bc){
messaging.SingleEmailMessage msg=new messaging.SingleEmailMessage();
string[] x= new string[]{'koteshkumar227@gmail.com'};
msg.setToAddresses(x);
msg.setsubject('Batch finish');
msg.setplaintextbody('Batch finished');
messaging.Email[] em=new messaging.Email[]{msg};
messaging.sendemail(em);
}
}
Ananomous window:
BatchExample be=new BatchExample();

pg. 113
database.executeBatch(be,5);
Output:

Example2:Updating and inserting the more number of records.(Multiple DML)


Global class BatchEx3 implements Database.Batchable<Sobject>{
Global Database.QueryLocator start(database.BatchableContext bc ){
Return Database.getQueryLocator('Select id,name,phone,Email__c,Description from
account');
}
Global void Execute(Database.BatchableContext bc,List<account> acc){
for(account a:acc){
a.phone='666666';
update a;
account b=new account();
b.Name='Chandana1';
b.Email__c='chandu1@gmail.com';
insert b;
contact c=new contact();
c.LastName='Bindu';
c.AccountId=b.id;
insert c;

}
Global void Finish(Database.Batchablecontext bc){}
}
Execute Ananamous Window:
BatchEx3 be=new BatchEx3();
database.executeBatch(be,50);
Output:

pg. 114
Example2: Create a batch Apex which fetch all the account Records from Account which are
owned by the user whose profile is System Admin and re-assign to User whose profile is ‘Ramana P’
Apex Class:
Global class ReassignBatch implements Database.Batchable<Sobject>{
Global Database.QueryLocator start(database.BatchableContext bc ){
Return Database.getQueryLocator('Select id,name,phone,Owner.name,Email__c from
account');
}
Global void Execute(Database.BatchableContext bc,List<account> acc){
user u=[select id,name from user where alias='rpa'];
for(account a:acc){
a.ownerid=u.id;
a.Email__c='ramana@gmail.com';
update a;
}
}
Global void Finish(Database.Batchablecontext bc){}
}
Execute Ananamous Window:
ReassignBatch be=new ReassignBatch();
database.executeBatch(be,100);
Output:

Example 3: Create batch apex with takes the query using construtor and update phone and Email
field as batch update
Apex Class:
Global class conbatch implements Database.Batchable<Sobject>{
global string query;
global conbatch (string q){
query=q;
}

Global Database.QueryLocator start(database.BatchableContext bc ){


Return Database.getQueryLocator(query);
}
Global void Execute(Database.BatchableContext bc,List<account> acc){
for(account a:acc){
a.phone='0000007';
a.Email__c='gangubhai@gmail.com';
update a;
}
}
Global void Finish(Database.Batchablecontext bc){}
}
Execute Ananamous Window:
conbatch be=new conbatch('Select id,name,phone,Owner.name,Email__c from account');

pg. 115
database.executeBatch(be,100);
Output:

Example4: Coverting VF page to PDF based on the Query and attaching to the record.
Apex code:
public class Sharukh {
public List<account> ac {set;get;}
public Sharukh(){
ac=[select name,id,Email__c from account];
}
public void addPDF1()
{
for(account a:ac){
PageReference pdfPage2 = new PageReference('/apex/Katrina');
Attachment attachment = new Attachment();
attachment.Name = 'RaviAttachment';
attachment.ContentType = 'application/pdf';
attachment.ParentId = a.Id;
attachment.Body = pdfPage2.getContentAsPdf();
insert attachment;
}
}
}
VF Page
<apex:page controller="Sharukh" >
<apex:form>
<apex:commandButton value="pdf" action="{!addPDF1}"/>
<apex:pageblock>
<apex:pageBlockTable value="{!ac}" var="b">
<apex:column value="{!b.id}"/>
<apex:column value="{!b.name}"/>
<apex:column value="{!b.Email__c}"/>
</apex:pageBlockTable>
</apex:pageblock>
</apex:form>
</apex:page>
Ananomous Window: (we can use button also to run the method ie. addPDF1)
Sharukh ss=new Sharukh();
ss.addPDF1();
Output: use anyone VFpage(Press Button) or Ananomous window

pg. 116
Example:Fetch the records of the selected user and send mail with PDF attachment
which contains all the records (which are fetched) yet to be tested
Apex Class:
public class DynamicAttach {
public list<account> acc {set;get;}
public list<user> u {set;get;}
public string x {set;get;}
public user x1 {set;get;}
public list<selectoption> op {set;get;}
public DynamicAttach(){
op=new list<selectoption>();
u=[select name from user];

for(user u1:u){
selectoption sp=new selectoption(u1.name,u1.name);
op.add(sp);

}
public void meth(){
acc=[select name,phone,Email__c,owner.name from Account where Owner.name=:x ];
x1=[select name,Email from user where name=:x ];
}
public void displaying(){
account a=[select name,Email__c,id from account where name='jumbo'];
pagereference p=new pagereference('apex/Ownerrecords');
attachment at=new attachment();

at.Name='kotesh';
at.ContentType='application/pdf';
at.Body=p.getContentAsPDF();
at.ParentId=a.id;

pg. 117
insert at;
Messaging.SingleEmailMessage msg=new Messaging.SingleEmailMessage();
list<messaging.EmailFileAttachment> at2=new list<messaging.EmailFileAttachment>();
string[] ss=new string[]{x1.Email};
msg.settoaddresses(ss);
msg.setsubject('koti');
messaging.EmailFileAttachment at1=new messaging.EmailFileAttachment();
at1.setfilename(at.name);
at1.setbody(at.body);
at2.add(at1);
msg.setfileattachments(at2);
messaging.Email[] sm =new messaging.email[]{msg};
messaging.sendEmail(sm);
}
}
VF Page:
<apex:page controller="DynamicAttach" >
<apex:form >
<apex:commandButton value="Display" action="{!displaying}"/>
<apex:selectlist value="{!x}">
<apex:selectOptions value="{!op}"></apex:selectOptions>
</apex:selectlist>
<apex:commandButton value="submit" action="{!meth}"/>
<apex:pageBlock >
<apex:pageBlockTable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.owner.name}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

Stateful Interface (in batch apex):


1. Changes made by one execute will not be transferred to another execute in the batch
apex.
2. If you want to transfer the state of the data from batch to another batch we need to
implement “Database.Stateful” interface.
3. When a batch apex class implements “Database.Stateful” interface, state of the non-static
data will be transferred from one execute to another execute method.

Example1: Create a custom object “optytemp” with custom field “Totalamount”.


Summarize the amount of all the opportunities and create a new optytemp record with amount as
summarized value of opportunity
If we don’t use Database.stateful interface the “Totalamount” will be Zero as execute method will
not pass the data to finish method.
Apex class:
global class Optystate implements Database.Batchable<Sobject>,Database.stateful {
global decimal total=0;
global database.QueryLocator start(database.BatchableContext bc){

pg. 118
return database.getQueryLocator('select name,amount from opportunity');
}
global void execute(database.BatchableContext bc,list<opportunity> op){
for(opportunity o:op){
if(o.Amount!=null){
total=total+o.amount;

}
}
system.debug('=================================== in execute'+total);
}
global void finish(database.BatchableContext bc){
system.debug('=================================== in finish'+total);
optytemp__c opty=new optytemp__c();
opty.name='Ravi';
opty.TotalAmount__c=total;
insert opty;
}
}
Ananamous window:
optystate os=new optystate();
database.executeBatch(os);
Output:

Example 2: Calling one batch apex from another and passing the value through constructor.
Apex Class:
global class Optystate implements Database.Batchable<Sobject>,Database.stateful {
global decimal total=0;
global database.QueryLocator start(database.BatchableContext bc){
return database.getQueryLocator('select name,amount from opportunity');
}
global void execute(database.BatchableContext bc,list<opportunity> op){
for(opportunity o:op){
if(o.Amount!=null){
total=total+o.amount;

}
}
system.debug('=================================== in execute'+total);
}
global void finish(database.BatchableContext bc){
system.debug('=================================== in finish'+total);
optytemp__c opty=new optytemp__c();
opty.name='Ravi';
opty.TotalAmount__c=total;

pg. 119
insert opty;
optystate2 os1=new optystate2(total);
database.executeBatch(os1);
}

}
global class Optystate2 implements Database.Batchable<Sobject> {
global decimal total2;
global Optystate2(decimal total1) {
total2=total1;
}
global database.QueryLocator start(database.BatchableContext bc){
return database.getQueryLocator('select name,amount from opportunity');
}
global void execute(database.BatchableContext bc,list<opportunity> op){
// system.debug('=================================== in finish'+total);
optytemp__c opty=new optytemp__c();
opty.name='vipin';
opty.TotalAmount__c=total2;
insert opty;
}
// system.debug('=================================== in execute'+total);

global void finish(database.BatchableContext bc){}


}
Ananamous window:
optystate os=new optystate();
database.executeBatch(os);
Output:

pg. 120
Schedule Apex:
1. If you want to run apex classes at a specific time then we use schedule apex.
2. If you want to schedule apex class, then apex class has to implement to “Schedulable”
Interface.
a. Syntax:
Public class example implements Schedulable {}
3. If any apex class which implements schedulable interface has to define “execute” method
a. Syntax:
Public void execute(schedulablecontext sc){}
4. Operation or Logic which you want to schedule should be defined in execute method.

SECS MINS HRS DAY_MONTH MONTH_YEAR DAY_WEEK YEAR


1 Job has to run at 10:30 am on March 10 , every year
0 30 10 10 3 ?
2 Job has to run at 8:00 PM on every Saturday.
0 0 20 ? * 7
Note: sun=1, sat=7
3 Job has to run on every second Friday at 6:20 AM
0 20 6 ? * 2#6
4 Job has to run on every last Friday at 5:30AM
0 30 5 ? * 6L
5 Job has to run on last working day at 6:45PM
0 45 18 LW * ?
Symbols and Meanings:
* Every (Everyday,EveryMonth, EveryHour,EveryMinute)
L Last (Lastday, LastMonth, lastFriday)
W Nearest working day
? Not Sure
, 3,5,7 (every 3rd,5th ,7th)

Example 1: Scheduing the apex at 1:53 PM on 7th Dec 2017, for Deleting contacts which are created
today
Apex Class:
public class Scheduleapex implements schedulable {
public void execute(SchedulableContext sc){
list<contact> accs=[select id,lastname from contact where createddate=TODAY];
delete accs;
}
}
Anananous window
Scheduleapex sa=new Scheduleapex();
string expression='0 53 13 7 12 ? 2017';
system.schedule('vipin',expression,sa);
Output:

pg. 121
Example2:Calling batch apex from schedule apex,and performing different dml operations.
Apex Class:
public class Scheduleapex implements schedulable {
public void execute(SchedulableContext sc){
list<contact> accs=[select id,lastname from contact where createddate=TODAY];
delete accs;
BatchEx3 be=new BatchEx3();
database.executeBatch(be,5);
}
}
Global class BatchEx3 implements Database.Batchable<Sobject>{
Global Database.QueryLocator start(database.BatchableContext bc ){
Return Database.getQueryLocator('Select id from account where createddate=Last_Month');
}
Global void Execute(Database.BatchableContext bc,List<account> acc){

for(integer i=0;i<50;i++){
account a=new account();
a.name='Sandeep';
a.Email__c='kavya@gmail.com';
insert a;
}
}

Global void Finish(Database.Batchablecontext bc){}


}
Ananomous Window:
Scheduleapex sa=new Scheduleapex();
string expression='0 42 14 7 12 ? 2017';
system.schedule('vipin1',expression,sa);
Output:contact records deleted and account records added

pg. 122
Example3:Calling Batch apex,Queueable apex,future method from Schedule apex and performing
various DML operations.
Apex Program:
Schedule Apex:
public class Scheduleapex implements schedulable {
public void execute(SchedulableContext sc){
list<contact> accs=[select id,lastname from contact where createddate=TODAY];
delete accs;
BatchEx3 be=new BatchEx3();//Calling batch apex
database.executeBatch(be,5);
ChainingApex2 ac=new ChainingApex2();//Calling Queueabe apex
system.enqueueJob(ac);
FutureAcc fa=new FutureAcc();//calling future method
fa.accss();

}
}
Batch Apex:
Global class BatchEx3 implements Database.Batchable<Sobject>{
Global Database.QueryLocator start(database.BatchableContext bc ){
Return Database.getQueryLocator('Select id from account where createddate=Last_Month');
}
Global void Execute(Database.BatchableContext bc,List<account> acc){

for(integer i=0;i<50;i++){
account a=new account();
a.name='Sandya';
a.Email__c='kavya@gmail.com';
insert a;
}
}
Global void Finish(Database.Batchablecontext bc){}
}
Queueable Apex:
public class ChainingApex2 implements Queueable {
public void execute(queueablecontext qc1){
list<account> acc2=[select name,phone,industry,fax,sic from account where
industry='banking'];
for(account b:acc2){
b.fax='143143143';

pg. 123
id x=qc1.getJobId();
b.Sic=x;
update b;
}
ChainingApex1 ca=new ChainingApex1();
id ids=system.enqueueJob(ca);
}
}
public class chainingApex1 implements Queueable {

public void execute(queueablecontext qc){


list<account> acc1=[select name,phone,industry,fax,description from account where
industry='banking'];
for(account a:acc1){
a.phone='9999999';
id x1=qc.getJobId();
a.description=x1;
update a;
}
}

}
Future Method:
public class FutureAcc {

public void acc(){


List<Account> acc=[select id,Email__c,fax,phone from Account where industry='banking'];
for(account a:acc){
// a.phone='+9999999';
a.Email__c='salman@gmail.com';
update a;
}
}
@future
public static void accs(){
List<Account> acc=[select id,Email__c,fax,phone from Account where industry='Education'];
for(account a:acc){
//a.fax='+911111111';
a.Email__c='katrina@gmail.com';
update a;
}
}
public void accss(){
acc();
accs();
}
}
Ananomous Window:
Scheduleapex sa=new Scheduleapex();
string expression='0 15 15 7 12 ? 2017';
system.schedule('Allall',expression,sa);

pg. 124
Output:

Example4:calling Schedule apex from Batch apex.(here batch job runs immediately and schedule
runs given interval of time).
Batch Apex:
Global class BatchEx3 implements Database.Batchable<Sobject>{
Global Database.QueryLocator start(database.BatchableContext bc ){
Return Database.getQueryLocator('Select id from account where createddate=Last_Month');
}
Global void Execute(Database.BatchableContext bc,List<account> acc){

for(integer i=0;i<50;i++){
account a=new account();
a.name='hasim';
a.Email__c='kavya1@gmail.com';
insert a;
}
}

Global void Finish(Database.Batchablecontext bc){


Scheduleapex sa=new Scheduleapex();
string expression='0 43 15 7 12 ? 2017';
system.schedule('bctosc',expression,sa);
}
}
Schedule Apex:
public class Scheduleapex implements schedulable {

pg. 125
public void execute(SchedulableContext sc){
list<contact> accs=[select id,lastname from contact where createddate=TODAY];
delete accs;

}
}
Ananomous window:
BatchEx3 be=new BatchEx3();
database.executeBatch(be,5);
Output:

Example5:calling schedule apex from schedule apex .


Schedule Apex:
public class Callschedule implements schedulable {
public void execute(SchedulableContext sc){
list<Account> accs=[select id,name from account where name='hasim' limit 10];
for(account a:accs){
a.name='hasim Sab';
update a;
}

Scheduleapex sa=new Scheduleapex();


string expression='0 17 16 7 12 ? 2017';
system.schedule('Sctosc11',expression,sa);
}
}
public class Scheduleapex implements schedulable {
public void execute(SchedulableContext sc){
list<contact> accs=[select id,lastname from contact where createddate=TODAY limit 10];
delete accs;

pg. 126
}
}
Ananomous window:
Callschedule sa=new Callschedule();
string expression='0 15 16 7 12 ? 2017';
system.schedule('sctosc22',expression,sa);
Output:

pg. 127
Example6:Calling schedule apex fromQueueabe apex.
Queueable Apex:
public class ChainingApex2 implements Queueable {
public void execute(queueablecontext qc1){
list<account> acc2=[select name,phone,industry,fax,sic from account where
industry='banking'];
for(account b:acc2){
b.fax='143143143';
id x=qc1.getJobId();
b.Sic=x;
update b;
}
ChainingApex1 ca=new ChainingApex1();
id ids=system.enqueueJob(ca);
Callschedule sa=new Callschedule();
string expression='0 34 16 7 12 ? 2017';
system.schedule('sctosc222',expression,sa);
}
}
public class chainingApex1 implements Queueable {

public void execute(queueablecontext qc){


list<account> acc1=[select name,phone,industry,fax,description from account where
industry='banking'];
for(account a:acc1){
a.phone='9999999';
id x1=qc.getJobId();
a.description=x1;
update a;
}
}
}
Schedule Apex:
public class Callschedule implements schedulable {
public void execute(SchedulableContext sc){
list<Account> accs=[select id,name from account where name='hasim' limit 10];

pg. 128
for(account a:accs){
a.name='hasim Sab';
update a;
}

Scheduleapex sa=new Scheduleapex();


string expression='0 37 16 7 12 ? 2017';
system.schedule('Sctosc111',expression,sa);
}
}
public class Scheduleapex implements schedulable {
public void execute(SchedulableContext sc){
list<contact> accs=[select id,lastname from contact where createddate=TODAY limit 10];
delete accs;

}
}
Ananomous Window:
ChainingApex2 ca=new ChainingApex2();
system.enqueueJob(ca);
Output:Queueabe job is completed first and then schedule jobs

pg. 129
EXTENSIONS
A controller extension is an Apex class that extends the functionality of a standard or custom
controller. Use controller extensions when:

 You want to leverage the built-in functionality of a standard controller but override one or
more actions, such as edit, view, save, or delete.
 You want to add new actions.
 You want to build a Visualforce page that respects user permissions. Although a controller
extension class executes in system mode, if a controller extension extends a standard
controller, the logic from the standard controller does not execute in system mode. Instead,
it executes in user mode, in which permissions, field-level security, and sharing rules of the
current user apply

Types of Extensions:

1.Standard controllers:it is used for performing operation on single record.


2.Standardsetcontrollers:it is used for performing operation on group of records.

pg. 130
Note:We con not override the existing pages directly,We have to use additional Vf page

pg. 131
STANDARD CONTROLLER
Example: methods of apexpages.standardcontroller

Apex Class:
public class allmethods {
public apexpages.StandardController cont {set;get;}

public account acc {set;get;}


public account acc1 {set;get;}
public allmethods(apexpages.StandardController controller){
cont=controller;
string[] ss= new string[]{'name','email__c','industry','rating'};
acc=(account)cont.getrecord();
}
public void savenew(){
insert acc;
acc.clear();
}
}
VF Page:
<apex:page standardController="account" extensions="allmethods">
<apex:form>
<apex:commandButton value="SAVE" action="{!save}"/><!---- This is applicable only for Edit
and detail page--->
<apex:commandButton value="cancel" action="{!cancel}"/> <!---- This is applicable only for
Edit and detail page--->
<apex:commandButton value="delete1" action="{!delete}"/> <!---- This is applicable only for
detail page--->
<apex:commandButton value="edit1" action="{!edit}"/> <!---- This is applicable only for detail
page--->
<apex:commandButton value="SAVEnew" action="{!savenew}"/> <!---- This is a custom
functionality so it is visible in the page--->

<apex:pageblock>
<apex:inputField value="{!account.name}"/>
<apex:inputField value="{!account.Email__c}"/>
<apex:inputField value="{!account.industry}"/>
<apex:inputField value="{!account.rating}"/>
</apex:pageblock>
</apex:form>
</apex:page>
Example1:Customizing “new”button with custom vf page in account object without extensions.
VF Page:
<apex:page standardController="account">
<apex:form>
<apex:pageBlock>
<apex:commandButton value="save" action="{!save}"/>
<apex:commandButton value="cancel" action="{!cancel}"/>
<apex:pageBlockSection columns="2">

pg. 132
<apex:pageBlockSectionItem>
<apex:outputLabel value="account name"/>
<apex:inputField value="{!account.name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Email"/>
<apex:inputField value="{!account.Email__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="industry"/>
<apex:inputField value="{!account.industry}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="rating"/>
<apex:inputField value="{!account.rating}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
The above page is linked to new button using below steps
Setup->Customize->Accounts->Buttons, Links, and Actions->Edit(New)->Visualforce page ->save

Output:

Example2:creating a functionality of “save&New” Button using Extensions(We cannot retrieve


existing save&new functionality ).
Apex Class:
public class SaveNew {
public account acc {set;get;}
public saveNew(apexpages.StandardController controller){
acc=new account();
}
public void savene(){
insert acc;

pg. 133
acc=new account();
}
}
VF Page:
<apex:page standardController="account" extensions="SaveNew">
<apex:form>
<apex:pageBlock>
<apex:commandButton value="save" action="{!save}"/>
<apex:commandButton value="save&New" action="{!saveNe}"/>
<apex:commandButton value="cancel" action="{!cancel}"/>
<apex:pageBlockSection columns="2">
<apex:pageBlockSectionItem>
<apex:outputLabel value="account name"/>
<apex:inputField value="{!acc.name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Email"/>
<apex:inputField value="{!acc.Email__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="industry"/>
<apex:inputField value="{!acc.industry}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="rating"/>
<apex:inputField value="{!acc.rating}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

One more Way of above program.Where we are directly accessing object fields.
Apex Class:
public class SaveNew {
public account acc {set;get;}
public saveNew(apexpages.StandardController cont){
acc=(Account)cont.getrecord();

}
public void savene(){
insert acc;
acc.clear();
}
}
VF Page:
<apex:page standardController="account" extensions="SaveNew">

pg. 134
<apex:form>
<apex:pageBlock>
<apex:commandButton value="save" action="{!save}"/>
<apex:commandButton value="save&New" action="{!saveNe}"/>
<apex:commandButton value="cancel" action="{!cancel}"/>
<apex:pageBlockSection columns="2">
<apex:pageBlockSectionItem>
<apex:outputLabel value="account name"/>
<apex:inputField value="{!account.name}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Email"/>
<apex:inputField value="{!account.Email__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="industry"/>
<apex:inputField value="{!account.industry}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="rating"/>
<apex:inputField value="{!account.rating}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

Example3:In account detail page create a button”Delete contacts” which displays and delete the
corresponding contacts of the particular account record.
Apex Class:
public class extension1 {
public id accid {set;get;}
public list<contact> contacts {set;get;}
public extension1(apexpages.StandardController contro){
accid=contro.getid();
contacts=[select id,lastname,phone from contact where accountid=:accid];
}
public pagereference deletecontact(){
database.delete(contacts,false);
pagereference p=new pagereference('/'+accid);
return p;
}
}
VF Page:
<apex:page standardController="Account" extensions="extension1" >
<apex:form >
<apex:pageBlock >

pg. 135
<apex:pageBlockButtons location="top">
<apex:commandButton value="delete" action="{!deletecontact}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!contacts}" var="a">
<apex:column value="{!a.lastname}"/>
<apex:column value="{!a.id}"/>
<apex:column value="{!a.phone}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Note:
1.Setup->Customize->Accounts->Buttons, Links, and Actions->New Button or link->Visualforce
page ->save

2.After this,Go to pagelayout of account object and add the Button to pagelayout and save.
3.if Button is not displayed in account detail page,then go to Profile and check account object
account layout.
Navigation: setup->Users->AssignProfile->accountLayout

pg. 136
Output:

Example4:Create a button in contact detail page(AccountDetails) which display the correspong


account detais along with the contact details.
Apex Class:
public class Contact_Extentions {

pg. 137
public Contact con{set;get;}
public Account acc {set;get;}
public Contact_Extentions(Apexpages.StandardController controller){
List<String> fields =new List<String>{'LastName','phone','fax','Email','accountid'};//which
fields you want to dislap and use
controller.addFields(fields);
con=(Contact)controller.getRecord();//Collects the data for the current record with above
fields only
acc=[select name,industry,phone from Account where id=:con.accountId];
}
}
VF Page:
<apex:page standardController="Contact" extensions="Contact_Extentions" >
<apex:form >
<apex:pageBlock title="Account">
<apex:pageBlockSection title="Account" collapsible="false" columns="1">
<apex:outputfield value="{!acc.name}" />
<apex:outputfield value="{!acc.industry}" />

</apex:pageBlockSection>
<apex:pageBlockSection title="Contact" collapsible="false" columns="1">
<apex:outputfield value="{!con.lastname}" />
<apex:outputfield value="{!con.firstname}" />
<apex:outputfield value="{!con.phone}" />
<apex:outputfield value="{!con.fax}" />
<apex:outputfield value="{!con.Email}" />
</apex:pageBlockSection>

</apex:pageBlock>
</apex:form>
</apex:page>
Output:

pg. 138
Example5: Create a button in contact detail page(AccountDetails) which display the correspong
account detais along with ”ALL” the corresponding contact records.
Apex Page:
public class Contact_Extentions {
public Contact con{set;get;}
public Account acc {set;get;}
public list<contact> cons {set;get;}
public Contact_Extentions(Apexpages.StandardController controller){
List<String> fields =new List<String>{'LastName','phone','fax','Email','accountid'};
controller.addFields(fields);
con=(Contact)controller.getRecord();
acc=[select name,industry,phone from Account where id=:con.accountId];
cons=[select lastname,phone,firstname,fax,Email,accountid from contact where
accountid=:con.accountid];
}
}
VF Page:
<apex:page standardController="Contact" extensions="Contact_Extentions" >
<apex:form >
<apex:pageBlock title="Account">
<apex:pageBlockSection title="Account" collapsible="false" columns="1">
<apex:outputfield value="{!acc.name}" />
<apex:outputfield value="{!acc.industry}" />

</apex:pageBlockSection >
<apex:pageBlockSection title="Contact">
<apex:pageBlockTable value="{!cons}" var="c">
<apex:column value="{!c.lastname}"/>
<apex:column value="{!c.firstname}"/>
<apex:column value="{!c.phone}"/>
<apex:column value="{!c.fax}"/>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

pg. 139
Example6:Overriding a “new” lead Button with custom functionality(Find duplicate before inserting
).
Apex Class:
public class DuplicateRec {
public lead l {set;get;}
public DuplicateRec(Apexpages.StandardController controller){
l=(Lead)controller.getRecord();
}
Public void FindDup(){
integer count=[select count() from Lead where Lastname=:l.LastName and
company=:l.company];
if(count>0)
{
Apexpages.Message msg=new Apexpages.Message(apexpages.Severity.ERROR,'Duplicate
Exist');
apexpages.addMessage(msg);
} else{
insert l;
l=new lead();
}
}
}
VFPage:
<apex:page standardController="lead" extensions="DuplicateRec" >

pg. 140
<apex:form>
<apex:pageMessages/>
<apex:commandButton value="Duplicate" action="{!FindDup}"/>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:outputLabel value="LastName"></apex:outputLabel>
<apex:inputField value="{!lead.Lastname}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Company"></apex:outputLabel>
<apex:inputField value="{!lead.company}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
One more Way
Apex Class:
public class DuplicateRec {
public lead l {set;get;}
public DuplicateRec(Apexpages.StandardController controller){
// l=(Lead)controller.getRecord();
l=new lead();
}
Public void FindDup(){
integer count=[select count() from Lead where Lastname=:l.LastName and
company=:l.company];
if(count>0)
{
Apexpages.Message msg=new Apexpages.Message(apexpages.Severity.ERROR,'Duplicate
Exist');
apexpages.addMessage(msg);
} else{
insert l;
l=new lead();
}
}
}
VF Page:
<apex:page standardController="lead" extensions="DuplicateRec" >
<apex:form>
<apex:pageMessages/>
<apex:commandButton value="Duplicate" action="{!FindDup}"/>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:outputLabel value="LastName"></apex:outputLabel>
<apex:inputField value="{!l.Lastname}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>

pg. 141
<apex:outputLabel value="Company"></apex:outputLabel>
<apex:inputField value="{!l.company}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
After this
1. 1.Setup->Customize->leads->Buttons, Links, and Actions->Edit(New)->Visualforce page ->save

2.Goto pagelayout of lead and Add the Button(Duplicate) and save


3.if Button is not displayed in lead detail page,then go to Profile and check lead object layout.
Navigation: setup->Users->AssignProfile->leadLayout

Output:

If duplicate not available then insert

Example 7: override “New”button of opportunity object with custom functionality. Add account
with corresponding opportunity and lead records.
Apex Class:
public class accoptycon {
public account acc {set;get;}
public contact con {set;get;}
public opportunity opty {set;get;}
public accoptycon(apexpages.StandardController controller){
acc=new account();
con=new contact();
opty=(opportunity)controller.getRecord();
}
public void save1(){

pg. 142
insert acc;
con.accountid=acc.id;
insert con;
opty.accountid=acc.id;
insert opty;
}
}
Apex Pages:
<apex:page standardController="opportunity" extensions="accoptycon">
<apex:form >
<apex:commandButton value="save1" action="{!save1}"/>
<apex:pageblock title="account">
name <apex:inputField value="{!acc.name}"/>
email <apex:inputField value="{!acc.Email__c}"/>
</apex:pageblock>

<apex:pageblock title="contact">
lastname <apex:inputField value="{!con.lastname}"/>
email <apex:inputField value="{!con.Email}"/>
</apex:pageblock>

<apex:pageblock title="opportunity">
name <apex:inputField value="{!opportunity.name}"/>
stagename <apex:inputField value="{!opportunity.stagename}"/>
closeddate <apex:inputField value="{!opportunity.closedate}"/>
</apex:pageblock>
</apex:form>
</apex:page>
Refer above for customizing the new button
Output:

pg. 143
STANDARDSETCONTROLLER:
Performing operations on group of records

Pagenation:
The process of putting numbers on the pages of the document by using strandardsetcontroller
pre-defined methods like. First,next,last,previous etc.
OR

pg. 144
The process of deviding a document into discrete pages, either electronic pages or printed pages.
Example1: extract all the opportunity record and display the records in the VF page as a set of 5
records. And add First,Last,next, previous buttons.
Apex Class:
public class pagenation {
public apexpages.StandardSetController controller {Set;get;}
public list<opportunity> getopty(){ //getopty will get the records used for VF page. it is a getter
method for opty variable.
list<opportunity> opty=(list<opportunity>)controller.getrecords();
return opty;
}
public pagenation(){
list<opportunity> opty=[select id,name,stagename,amount from opportunity];
controller=new apexpages.StandardSetController(opty);
controller.setPageSize(5);
}
}

VF Page
<apex:page controller="pagenation">
<apex:form>
<apex:pageblock title="example" id="pb">
<apex:pageBlockButtons location="bottom">

<apex:commandButton value="Previous" action="{!controller.previous}" reRender="pb"


rendered="{! controller.hasPrevious}" />
<apex:commandButton value="first" action="{!controller.First}" reRender="pb"
rendered="{! controller.hasPrevious}" />
<apex:commandButton value="Next" action="{!controller.next}" reRender="pb"
rendered="{! controller.hasNext}" />
<apex:commandButton value="Last" action="{!controller.last}" reRender="pb"
rendered="{! controller.hasNext}" />

</apex:pageBlockButtons>
<apex:pageblocktable value="{!opty}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.stagename}"/>
<apex:column value="{!a.amount}"/>

</apex:pageblocktable>
&nbsp;&nbsp; &nbsp;&nbsp;
{!controller.pageNumber * controller.pagesize} &nbsp;&nbsp; of &nbsp;&nbsp; {!
controller.resultSize}
</apex:pageblock>
</apex:form>
</apex:page>
Output:

pg. 145
Example2:Parent child with pagination
Apex Class:
public class AccPagination {
public apexpages.StandardSetController controller {Set;get;}
public apexpages.StandardSetController controller1 {Set;get;}
public list<contact> con {set;get;}
public list<account> getacc(){
con.clear();
list<account> acc=(list<account>)controller.getrecords();
for(account b:acc){
for(contact c:b.contacts){
con.add(c);
}

}
return acc;
}
public Accpagination(){
con=new list<contact>();
list<Account> acc=[select id,name,Email__c,phone,(select lastname,phone,accountid from
contacts) from account where name='Rajyam' or name='kavyam'];
controller=new apexpages.StandardSetController(acc);
controller.setPageSize(1);
}
}
VF Page:
<apex:page controller="AccPagination">
<apex:form >
<apex:pageblock title="account" id="pb">
<apex:pageBlockButtons location="bottom">

<apex:commandButton value="Previous" action="{!controller.previous}"


reRender="pb,pb2" rendered="{! controller.hasPrevious}" />
<apex:commandButton value="first" action="{!controller.First}" reRender="pb,pb2"
rendered="{! controller.hasPrevious}" />
<apex:commandButton value="Next" action="{!controller.next}" reRender="pb,pb2"
rendered="{! controller.hasNext}" />
<apex:commandButton value="Last" action="{!controller.last}" reRender="pb,pb2"
rendered="{! controller.hasNext}" />

</apex:pageBlockButtons>
<apex:pageblocktable value="{!acc}" var="a">

pg. 146
<apex:column value="{!a.name}"/>
<apex:column value="{!a.Email__C}"/>
<apex:column value="{!a.phone}"/>
</apex:pageblocktable>
&nbsp;&nbsp; &nbsp;&nbsp;
{!controller.pageNumber * controller.pagesize} &nbsp;&nbsp; of &nbsp;&nbsp; {!
controller.resultSize}
</apex:pageblock >
<apex:pageBlock title="contacts" id="pb2">
<apex:pageblocktable value="{!con}" var="c">
<apex:column value="{!c.lastname}"/>
<apex:column value="{!c.phone}"/>
</apex:pageblocktable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:

Example3:Delete the selected records from the list view page from account object using
standardSetController.
Apex Class:
public class MassDeL {
public list<account> acc {set;get;}
public MassDel(apexpages.StandardSetController controller){
string[] fields=new string[]{'name','phone','industry','rating'};
controller.addFields(fields);
acc=(list<account>)controller.getSelected();//This will fetch the selected records with above
mentioned fields only from the list view.
}
public pagereference DellAcc(){
database.delete(acc,false);
pagereference p=new pagereference('/001/o');//001/o is the id of the account object.
return p;
}
}
VF Page:
<apex:page standardController="Account" extensions="MassDeL" recordSetVar="items">
<apex:form>
<apex:pageBlock title="Account">
<apex:pageBlockButtons location="top">
<apex:commandButton value="MassDel" action="{!DellAcc}"/>
</apex:pageBlockButtons>

pg. 147
<apex:pageBlockTable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.phone}"/>
<apex:column value="{!a.industry}"/>
<apex:column value="{!a.rating}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
After this
1.setup->Build->customize->accounts->Buttond,links and actions->new Button or link

2. 1.setup->Build->customize->accounts->Search Layout->Accounts List View->save

Output:

pg. 148
Example4: create a button in lead list view page which updates the seleted records with Rating as
‘cold’.
Apex Class
public class UpdLead {
public list<lead> leads {set;get;}
public UpdLead(apexpages.StandardSetController controller){
string[] fields=new string[]{'lastname','company','status','rating'};
controller.addfields(fields);
leads=(list<lead>)controller.getselected();
}
public pagereference Uplead(){
for(lead l:leads){
l.rating='cold';
update l;
}
pagereference p=new pagereference('/00Q/e');
return p;
}
}
VF Page:
<apex:page standardController="lead" extensions="UpdLead" recordSetVar="items">
<apex:form >
<apex:pageBlock title="lead">
<apex:pageBlockButtons location="top">
<apex:commandButton value="Massupd" action="{!Uplead}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!leads}" var="a">
<apex:column value="{!a.lastname}"/>
<apex:column value="{!a.company}"/>
<apex:column value="{!a.status}"/>
<apex:column value="{!a.rating}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Creation of button is same as above example
Output:

pg. 149
Example6: Create a picklist in the VF page which containts the options of the List view options and
display the id of the selected option. (using getfilterid and getlistviewoptions of the controller)
Apex Page:
public class AllPicOpty {
public list<selectoption> options {set;get;}
public string filterid {set;get;}
public AllPicOpty(apexpages.StandardSetController controller){
options=controller.getlistviewoptions(); // it will get all the options of the list view page
picklist
filterid=controller.getFilterId(); //This will get the id of the selected option in the picklist of
the current page
}
}
VF Page:
<apex:page standardController="opportunity" extensions="AllPicOpty" recordSetVar="items">
<apex:form>
<apex:selectList size="1" value="{!filterid}">
<apex:selectOptions value="{!options}"></apex:selectOptions>
</apex:selectList>
</apex:form>
</apex:page>
Output:

Example5:Create a button to share selected accountrecord to other user(‘Ramana P’).


Note:Account OWD is Private
Apex Class:
public class ApexShare {
public list<account> acc {set;get;}
public Apexshare(apexpages.StandardSetController cont){
string[] fields=new string[]{'name','email__c','industry'};
cont.addfields(fields);
acc=(list<account>)cont.getselected();
}
public void sharerec(){
user u=[select name,id from user where alias='rpa'];
List<AccountShare> shareList = new List<AccountShare>();
for(account a:acc) {
AccountShare ass = new AccountShare();
ass.AccountId=a.id;
ass.AccountAccessLevel='Read';
ass.UserOrGroupId=u.id;
ass.OpportunityAccessLevel='Read';
shareList.add(ass);

pg. 150
}
insert shareList;
}
}

VF Page:
<apex:page standardController="account" extensions="ApexShare" recordSetVar="accounts" >
<apex:form>
<apex:pageBlock title="account">
<apex:pageBlockButtons location="top">
<apex:commandButton value="Trnsfer" action="{!sharerec}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!acc}" var="a">
<apex:column value="{!a.name}"/>
<apex:column value="{!a.Email__c}"/>
<apex:column value="{!a.industry}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Creation of button is sama as above.
Output:

pg. 151
SCHEMA PROGRAMMING
It is used to get metadata (organization level) properties:

pg. 152
Example1:How to get the properties of an object(Account).
Apex Class:
public class schema1 {
public string results {set;get;}
public Map<string,object> resmap{set;get;}
public schema1(){
resmap=new Map<string,object>();
schema.describesobjectresult res=account.sobjecttype.getdescribe();
results=''+res;
//if u want to display in map
resmap=new Map<string,object>();
resmap.put('label',res.getlabel());
resmap.put('name',res.getname());
resmap.put('Read',res.isAccessible());
resmap.put('Create',res.isCreateable());
resmap.put('update',res.isUpdateable());
resmap.put('Delate',res.isDeletable());
}
}
VF Page:
<apex:page controller="schema1">

pg. 153
{!results}<br/><br/><br/><br/>
<form>
<apex:pageBlock title="Account">
<apex:pageBlockTable value="{!resmap}" var="a">
<apex:column value="{!a}"/>
<apex:column value="{!resmap[a]}"/>
</apex:pageBlockTable>
</apex:pageBlock>

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

Example2:Fetch all the fields from Object(Account) and display in picklist.


Apex Class:
public class Schema2 {
public string results {set;get;}
Public List<selectoption> fields {set;get;}
public schema2(){
fields= new List<selectoption>();
schema.describesobjectresult res=account.sobjecttype.getdescribe();
results=''+res;
Map<string,schema.SObjectField> fldmap=res.fields.getmap();
set<string> keys=fldmap.keySet();
for(string s:keys){
selectoption op=new selectoption(s,s);
fields.add(op);
}
}
}
VF Page:
<apex:page controller="Schema2">
<apex:form>
<apex:selectList size="1">
<apex:selectOptions value="{!fields}">
</apex:selectOptions>
</apex:selectList>
</apex:form>
</apex:page>
Output:

pg. 154
Example3:Fetch all the childobjects of parent object(Account).
Apex Class:
public class schema1 {
public list<selectoption> options {set;get;}
public string y {set;get;}
public schema1(){
options=new list<selectoption>();
schema.describesobjectresult res=account.sobjecttype.getdescribe();
List<Schema.ChildRelationship> c= res.getChildRelationships();

for(Schema.ChildRelationship c1:c) {
schema.sobjecttype cr=c1.getchildSobject();
y=''+cr;
selectoption s=new selectoption(y,y);
options.add(s);
}
}
}
VF Page:
<apex:page controller="schema1">
<apex:form>
<apex:selectList size="1">
<apex:selectOptions value="{!options}"> </apex:selectOptions>
</apex:selectList>
</apex:form>
</apex:page>
Output:

Example4:Fetch the values of industry picklist and Display picklist in VF Page.


Apex Class:
public class schema1 {
public list<selectoption> options {set;get;}
public schema1(){
options=new list<selectoption>();
Schema.DescribeFieldResult c= Account.industry.getDescribe();
list<schema.PicklistEntry> entry=c.getpicklistvalues();
for(schema.PicklistEntry c1:entry) {
selectoption s=new selectoption(c1.getvalue(),c1.getlabel());
options.add(s);
}

}
}
VF Page:
<apex:page controller="schema1">
<apex:form>
<apex:selectList size="1">
<apex:selectOptions value="{!options}"> </apex:selectOptions>

pg. 155
</apex:selectList>
</apex:form>
</apex:page>
Output:

Example5:Fetch all the objects in organization and display in picklist.


Apex Class:
public class SchemaAllObj {
public Map<String, Schema.SObjectType> gd {set;get;}
public list<selectoption> options {set;get;}
public SchemaAllObj(){
gd= Schema.getGlobalDescribe();
options=new list<selectoption>();
set<string> ss=gd.keyset();
for(string s:ss){
selectoption op=new selectoption(s,s);
options.add(op);
}

}
}
VF Page:
<apex:page controller="SchemaAllObj">
<apex:form>

<apex:selectList size="1">
<apex:selectOptions value="{!options}"></apex:selectOptions>
</apex:selectList>

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

Example6:Fetch all the objects from the org and display in picklist .Based on the selected object
dispaly corresponding fields in another picklist.

pg. 156
Apex Class:
public class SchemaAllObj {
public Map<String, Schema.SObjectType> gd {set;get;}
public list<selectoption> options {set;get;}
public list<selectoption> fields {set;get;}
public string y {set;get;}
public SchemaAllObj(){
gd= Schema.getGlobalDescribe();
options=new list<selectoption>();
fields=new list<selectoption>();
set<string> ss=gd.keyset();
for(string s:ss){
selectoption op=new selectoption(s,s);
options.add(op);
}
}
public void Allfields(){
schema.sobjecttype obj=gd.get(y);
schema.describesobjectresult res=obj.getdescribe();
Map<string,schema.SObjectField> fldmap=res.fields.getmap();
for(string c:fldmap.keySet()){
selectoption sss=new selectoption(c,c);
fields.add(sss);
}
}
}
VF Page:
<apex:page controller="SchemaAllObj">
<apex:form>

<apex:selectList size="1" value="{!y}">


<apex:actionSupport event="onchange" action="{!Allfields}"/>
<apex:selectOptions value="{!options}"></apex:selectOptions>
</apex:selectList>

<apex:selectList size="1" >


<apex:selectOptions value="{!fields}"></apex:selectOptions>
</apex:selectList>

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

pg. 157
Example7: fetch all the objects from Org and display in a picklist, display the corresponding child for
the selected objects in picklist and for selected child object display the fields in another picklist.
Apex Class:
public class SchemaAllObj {
public Map<String, Schema.SObjectType> gd {set;get;}
public list<selectoption> options {set;get;}
public list<selectoption> fields {set;get;}
public list<selectoption> childobj {set;get;}
public string y {set;get;}
public string x {set;get;}
public string z {set;get;}
public SchemaAllObj(){
gd= Schema.getGlobalDescribe();
options=new list<selectoption>();
fields=new list<selectoption>();

set<string> ss=gd.keyset();
for(string s:ss){
selectoption op=new selectoption(s,s);
options.add(op);
}

}
public void childs(){
childobj=new list<selectoption>();
schema.sobjecttype obj1=gd.get(y);
schema.describesobjectresult res1=obj1.getdescribe();
List<Schema.ChildRelationship> ccc= res1.getChildRelationships();
for(Schema.ChildRelationship c1:ccc) {
schema.sobjecttype cr=c1.getchildSobject();
x=''+cr;
selectoption s=new selectoption(x,x);
childobj.add(s);
}
}

public void Allfields(){


schema.sobjecttype obj=gd.get(z);
schema.describesobjectresult res=obj.getdescribe();

pg. 158
Map<string,schema.SObjectField> fldmap=res.fields.getmap();
for(string c:fldmap.keySet()){
selectoption sss=new selectoption(c,c);
fields.add(sss);
}
}
}
VF Page:
<apex:page controller="SchemaAllObj">
<apex:form >

<apex:selectList size="1" value="{!y}">


<apex:actionsupport event="onchange" action="{!childs}"/>
<apex:selectOptions value="{!options}"></apex:selectOptions>
</apex:selectList>

<apex:selectList size="1" value="{!z}" >


<apex:actionsupport event="onchange" action="{!Allfields}"/>
<apex:selectOptions value="{!childobj}"></apex:selectOptions>
</apex:selectList>

<apex:selectList size="1" >


<apex:selectOptions value="{!fields}"></apex:selectOptions>
</apex:selectList>

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

Example 8: Fetch all the custom objects in the organization and display in the picklist.
Apex Class:
public class customObject {
public map<string,schema.sobjecttype> de {Set;get;}
public list<selectoption> options {Set;get;}
public customobject(){
de=schema.getGlobalDescribe();
options=new list<selectoption>();
set<string> keys=de.keySet();
for(string s:keys){
schema.SObjectType obj =de.get(s);
schema.DescribeSObjectResult objres=obj.getDescribe();
if(objres.iscustom()){
selectoption op=new selectoption(s,s);
options.add(op);

pg. 159
}

}
}
}
VF Page
<apex:page controller="customobject">
<apex:form>
<apex:pageblock>
<apex:selectList size="1">
<apex:selectOptions value="{!options}"></apex:selectOptions>
</apex:selectList>
</apex:pageblock>
</apex:form>
</apex:page>
Output

Flows and Plugins


Flows:
When the process involves the number of pages, when the data need to be transferred between
the pages. We prefer to uses flows.
Plugin:
Plugin is built-in interface that allows you to write business logic and to pass data between your
organization and a specified flow.
Process [Plugin]

Note:plugin Interface is not mandatory.

pg. 160
Process.Plugindescriberesult:
This class contains all the properties of all the list of input/ouput parameters.

Public class plugindescriberesult{


List<process.plugindescriberesult.inputparameter> inputparameters;
List<process.plugindescriberesult.outputparameter> outputparameters;
}
Process.plugindescriberesult.inputparameter
This class contains all the input parameters

process.plugindescriberesult.inputparameter(param1,param2,param3);

param1: name of input parameter


param2: datatype of input parameter
param3: required value/not required value.\

Example:
process.plugindescriberesult.inputparameter ip1= new
process.plugindescriberesult.inputparameter(‘Exp’,
process.plugindescriberesult.inputparameter.decimal,true);

list<process.plugindescriberesult.inputparameter> inputs= new


list<process.plugindescriberesult.inputparameter>{ip1,ip2}

Process.plugindescriberesult.outputparameter
This class contains all the output parameters

process.plugindescriberesult.outputparameter(param1,param2);

param1: name of output parameter


param2: datatype of output parameter

Example:

pg. 161
process.plugindescriberesult.outputparameter op1= new process.plugindescriberesult.
outputparameter(‘Exp’, process.plugindescriberesult. outputparameter.decimal);

list<process.plugindescriberesult. outputparameter> outputs= new


list<process.plugindescriberesult. outputparameter>{op1,op2}

Process.pluginrequest
This class will gives information about all the input parameters we have received from flow.

Public class process.pluginrequest {


Map<string,object> inputparameters;
}
Example:
Process.pluginrequest request= new process.pluginrequest();
String city=request.inputparameter.get(‘city’);
Decimal exp=request.inputparameter.get(‘exp’);
Process.pluginresult.
This class will gives information about all the output parameters we have received from plugin.

Public class process.pluginresult {


Map<string,object> outputparameters;
}
Example:
Process.pluginresult result= new process.pluginresult();
Decimal bonus=result.outputparameter.get(‘bonus’);
Decimal salary=result.outputparameter.get(‘salary’);
Example 1: Create a flow to capture Experience and salary in the first screen, pass the captured
values to the Plugin for calculation of bonus and total and display the output in the final screen.
Apex class:
public class PluginExample3 implements Process.Plugin {
public Process.PluginResult invoke(Process.PluginRequest request){
Decimal salary=(Decimal)request.inputparameters.get('salary');
Decimal exp=(Decimal)request.inputparameters.get('exp');
Decimal bonus,total;
if( exp >3){
bonus=(salary*15)/100;
total=bonus+salary;
}else{
bonus=(salary*10)/100;
total=bonus+salary;
}
Map<String,Object> outputMap=new Map<String,Object>();
outputMap.put('total',total);
outputMap.put('bonus',bonus);
Process.PluginResult result=new Process.PluginResult(outputMap);
return result;
}
public Process.PluginDescribeResult describe(){
Process.PluginDescribeResult result=new Process.PluginDescribeResult();

pg. 162
Process.PluginDescribeResult.Inputparameter ip1=new
Process.PluginDescribeResult.inputParameter('salary',Process.PluginDescribeResult.ParameterTyp
e.Decimal,true);
Process.PluginDescribeResult.Inputparameter ip2=new
Process.PluginDescribeResult.inputparameter('exp',Process.PluginDescribeResult.parametertype.
Decimal,true);
Process.PluginDescribeResult.Outputparameter op1=new
Process.PluginDescribeResult.outputparameter('total',Process.PluginDescribeResult.Parametertyp
e.Decimal);
Process.PluginDescribeResult.Outputparameter op2=new
Process.PluginDescribeResult.Outputparameter('bonus',Process.PluginDescribeResult.ParameterT
ype.Decimal);
List<Process.PluginDescribeResult.Inputparameter> inputs =new
List<Process.PluginDescribeResult.Inputparameter>{ip1,ip2};
List<Process.PluginDescribeResult.Outputparameter> outputs=new
List<Process.PluginDescribeResult.Outputparameter>{op1,op2};
result.inputparameters=inputs;
result.outputparameters=outputs;
return result;
}
}
Flow:

pg. 163
After saving the flow, go to “close” and activate the flow then run the flow.

DML Operation with Flow


Example 1: Creation of account record with the captured data from the flow.
FLOW:

pg. 164
Output: Save and activate and run

pg. 165
Example 2: Update the record with the captured data from the flow.
FLOW

pg. 166
Output: Save and activate and run

Example3: Delete record based on data captured in the flow.

pg. 167
Output: Save and activate and run

pg. 168
Learnings:I
Topic Issue and Solution
Action Issue: Action support was not function in selectlist
Support Solution: we have to place the action support between Selectlist and Selectoption.
Parent Child The childre object name should be plural and extended by __r(i.e Courses__r)
Soql (in
custom)
Parent Child The child object name should be plural.(i.e contacts)
Soql(standard)
Repeat in Repeat is used to display child records for every corresponding parent record.
column
Initializing Its good practice to initialize the object inside the method if not it may give error.
object
Triggers Display Error message from Triggers.
c.addError('Enter account name');
Email services we can not use more than one "setToAddresses", use an array for multiple emails
string[] options=new string[]{mail,lee.Email};

Before update No need to use ‘update’ command when performing before update

pg. 169

You might also like