Triggers
Trigger:
Apex
can be invoked through the use of triggers. A trigger is Apex code that executes before or after the
following types of
operations:
• insert
• update
• delete
• merge
• upsert
• undelete
Triggers
can be divided into two types:
• Before
triggers can be used to update or
validate record values before they are saved to the database.
Ø The first being that you can perform data
validation and reject a record before it is committed to the database, meaning
there is no cost to performance by the system having to roll back an update.
Second, you can update fields or set default values for a record without having
to initiate another DML command.
Ø For example the code below illustrates setting
a default value on a record. No DML required.
trigger beforetriggerex on Account
(Before insert,before update) {
//setting
default values in account
for(Account a : Trigger.new){
a.rating = 'hot';
}
// setting validation rules
for(account a: trigger.new){
if(a.type == 'prospect'){
a.type.adderror('change account type');
}
}
//fields update
for(account a : trigger.new){
if(a.phone != null){
a.fax = a.phone;
a.website = 'www.salesforce.com';
}
}
}
• After
triggers can be used to access field
values that are set by the database (such as a record's Id or
lastUpdated field), and to affect changes in other records.
trigger
createNewAccountOpportunity on Account (after insert) {
List<Opportunity> listOpportunities =
new List<Opportunity>();
for (Account a : trigger.new) {
Opportunity o= new Opportunity();
o.Name = a.Name;
o.AccountId = a.Id;
o.StageName= 'prospecting';
o.CloseDate = System.today() + 30;
listOpportunities.add(o);
}
insert listOpportunities ;
}
Triggers
trigger PhoneequalFax on Account (before insert, before update) {
ReplyDeletefor(Account a:trigger.new){
if(a.phone!='Null'){
a.phone=a.fax; a.website='www.salesforcemylove.com';
}
}
}
I am getting only website field updated but i want i want to update phone number = fax number as well...please suggest
if(a.fax!=null){
Deletea.phone = a.fax;
}
================