string
age;
if(age==' '){
[Link]('hellooooooooooo');
}
string age;
if(age==null){
[Link]('hai::::::::::::::::');
}
salesforce apex null check
whenever new student registered update the count in
respective trainer record
what to do? action? update trainer record --> i.,
when to do? event--> after insert-->student
student sobject
trainer sobject
create count (number type of field) in trainer object
in student object create lookup r/s type of field to link
with trainer.
trigger abcd on student__C(after insert){
list<string> trainerids = new list<string>();
for(student__C x:[Link])
{[Link](x.lookupfield__c);}
list<trainer__C> myt=[select id,name,count__c from
trainer__c where id IN :trainerids];
list<trainer__C> dummy = new list<trainer__C>();
for(trainer__C k:myt){
k.count__C++;
[Link](k);}
update dummy;
update myt; //what happens if i write? }
whenever student registered send email to respective
trainer
whenever trainer mobile number modified then send
email to respective students
whenever student changed his trainer then decrease
count to previous trainer and increase count to new
trainer
if the student record deleted then decrease count in
trainer
custom-rollup summary
========================================
========================================
=========
1. When ever new Account is inserted with Industry
as 'Banking ' then set the phone
as '888'
========================================
========================================
=========
Trigger:
trigger phoneUpdate on Account (before insert) {
for(Account a: [Link]){
if([Link]=='Banking'){
[Link]='888';
}
}
}
@istest
public class edokati{
testmethod static void kkk(){
account obj = new account();
[Link]='gggg';
[Link]='banking';
insert obj;
}
}
Test Class :
@isTest
private class PhoneTest {
testmethod static void testme(){
Account acc=new Account();
[Link]='capital';
[Link]='Banking';
try{
insert acc;
}catch(Exception e){
}
Account a=[select id,phone from Account where
id=:[Link]];
[Link]([Link],'888');
}
}
========================================
========================================
========
2. When ever new lead is created , calculate the
leadscore using before inserting
Field Name NOT NULL NULL
Email 10 0
Phone 10 0
Industry 20 0
Note : First Create a custom field LeadScore on
Lead object
========================================
========================================
========
Trigger :
trigger leadscoreTrig on Lead (before insert) {
for(Lead ld: [Link]){
Integer count=0;
if([Link]!=''&& [Link]!=null){
count=count+10;
}
if([Link]!='' && [Link]!=null ){
count=count+10;
}
if([Link]!='' && [Link]!=null){
count=count+20;
}
ld.leadScore__c=count;
}
}
Test Class :
@isTest
private class LeadScoreTest {
@isTest
static void testme(){
Lead ld=new Lead();
[Link]='satish';
[Link]='Capital';
[Link]='111';
[Link]='javasfdc@[Link]';
[Link]='Banking';
try{
insert ld;
}catch(Exception e){
}
Lead newLead=[select LeadScore__c from
Lead where id=:[Link]];
[Link](newLead.LeadScore__c,40);
}
}
========================================
========================================
========
[Link] a Queue on Lead object as Banking Queue
with users ( satish) :
Create a Queue on Lead object as Energy Queue
with Users
Scenario: When a new Lead is inserted based on
the industry field value assign it
corresponding queue
Industry-Banking--assing owner of the record
as Banking queue
Industry-Energy---Assign owner of the record
as Energy Queue
Industry other than Banking and Energy user
who ever has created the
record he should be the owner
========================================
========================================
========
========================================
========================================
=======
[Link] ever new Account is created with
AnnualReneue more than 50 Lacs and Industry
as Energy then create a new opportunity for this
account with
OpportunityName as AccountName
StageName as Prospecting
CloseDate as Today+30 days
========================================
========================================
======
trigger AccountInsert on Account (after insert) {
List<Opportunity> optyList=new
List<Opportunity>();
for(Account a: [Link]){
if([Link]=='Energy' && [Link]
>5000000){
Opportunity op=new Opportunity();
[Link]=[Link];
[Link]='Prospecting';
[Link]=[Link]()+20;
[Link]=[Link];
[Link](op);
}
}
insert optyList;
}
TestClass :
@isTest
private class AccountInsertTest {
@isTest
static void testme(){
Account a1=new Account();
[Link]='Test';
[Link]='Energy';
[Link]=9000000;
try{
insert a1;
}catch(Exception e){
}
Integer count=[select count() from Opportunity];
if([Link]=='Energy' &&
[Link]>5000000)
[Link](count,1);
else
[Link](count,0);
}
}
========================================
========================================
=======
5. When ever new Account record is created with
Industry as "Education ' and
annualRevenue as 10 Lacs then add user karthic
as AccountTeamMember
AccountTeamMember :
[Link] : Id of the record on which we are
creating teammember
[Link] : Id of the user whom we are adding as
Teammember
[Link] : choose some value pickList
field of TeamMemberRole
[Link] : Type of Access you are
providing on Account for the team
member
Posible values are 'Read' ,'Edit','ALL'
5. OpportunityAccessLevel:
6. CaseAccessLevel :
7. COntactAccessLevel :
Note : Before we implement this trigger enable the
AccountTeams
setup
|----Build
|----Customize
|------Accounts
|------AccountTeams
1. Enable AccountTeam
2. Add the AccountTeams as related list on all the
pageLayouts
========================================
========================================
======
Trigger:
trigger AccountTeamTrig on Account (after insert) {
List<AccountTeamMember> teams=new
List<AccountTeamMember>();
User u=[select id from User where alias='knair'];
for(Account a:[Link]){
if([Link]=='Education' && [Link]
>1000000){
AccountTeamMember atm=new
AccountTeamMember();
[Link]=[Link];
[Link]=[Link];
[Link]='Account Manager';
[Link]='Edit';
[Link](atm);
}
}
insert teams;
}
TestClass :
@isTest
private class AccountTeamTest {
@isTest
static void testme(){
User u=[select id from User where alias='knair'];
Account a=new Account();
[Link]='Education';
[Link]='capital';
[Link]=1300000;
try{
insert a;
}catch(Exception e){
[Link](e);
}
AccountTeamMember atm=[select
userId,AccountId,AccountAccessLevel from
AccountTeamMember where AccountId=:[Link]];
if([Link]=='Education' &&
[Link]>1000000){
[Link]([Link],[Link]);
[Link]([Link]
el,'Edit');
[Link]([Link],'
Account Manager');
}else{
[Link](atm,null);
}
}
}
========================================
========================================
======
6. When ever new opportuntiy is created with
StageName as 'closed Won ' then
add karthic as OpportunityTeamMember
OpportunityTeamMember :
OpportunityId :
UserId :
OpportunityAccessLevel :
TeamMemberRole :
Note : Before we implement this enable
opportunityTeams
setup
|----Build
|----Customize
|------Opportunitys
|------OpportunityTeams
1. Enable OpportuntiyTeam
2. Add the opportunitytTeams as related list on all
the pageLayouts
========================================
========================================
=======
Trigger:
trigger opptyTeamTrig on Opportunity (after insert) {
List<OpportunityTeamMember> teams=new
List<OpportunityTeamMember>();
User u=[select id from User where alias='knair'];
for(Opportunity op:[Link]){
if([Link]=='closed Won'){
OpportunityTeamMember otm=new
OpportunityTeamMember();
[Link]=[Link];
[Link]=[Link];
[Link]='Account Manager';
[Link]='Edit';
[Link](otm);
}
}
insert teams;
}
TestClass :
@isTest
private class OpportunityTeamTrig {
@isTest
static void testme(){
User u=[select id from User where alias='knair'];
Opportunity a=new Opportunity();
[Link]='Test';
[Link]='closed won';
[Link]=[Link]()+5;
try{
insert a;
}catch(Exception e){
[Link](e);
}
OpportunityTeamMember atm=[select
userId,OpportunityId,OpportunityAccessLevel from
OpportunityTeamMember where OpportunityId=:[Link]];
if([Link]=='closed won' ){
[Link]([Link],[Link]);
[Link]([Link]
Level,'Edit');
[Link]([Link],'
Account Manager');
}else{
[Link](atm,null);
}
}
}
========================================
========================================
=======
7. When ever new Account record is created with
Account Type as 'prospect ' then
create a new contact for this account with following
data
Contact lastname as Account Name
COntact Phone as Account Phone
========================================
========================================
===
Trigger:
trigger example on Account( after insert ){
List<Contact> contacts=new List<Contact>();
for(Account a: [Link]){
if([Link]=='Prospect'){
Contact c=new Contact();
[Link]=[Link];
[Link]=[Link];
[Link]=[Link];
[Link](c);
}
}
insert contacts;
}
Test Class :
@isTest
private class AccountTest{
@isTest
static void testme(){
Account a=new Account();
[Link]='Test';
[Link]='Prospect';
try{
insert a;
}catch(Exception e){
}
Integer count=[select count() from
Contact];
if([Link]=='Prospect'){
[Link](count,1);
}else{
[Link](count,0);
========================================
========================================
========
Sharing rules on the sobject are stored in thier
corresponding share objects
Ex:
Account ----AccountShare
Contact-----ContactShare
Opportunity---OpportuntiyShare
Customer__c-----Customer_Share
Transaction _ _ c------Transaction_share
Q::When do you share a record ?
When OWD on a object is Private /Public Read and
user doesnt have read and write access
on a record
Q:: When we want to share a record using apex what
field are needed
1. Which record : OpportunityId
2. With whom : UserOrGroupId
3. What type of access :OpportunityAccessLevel
4. Reason for sharing :RowCause
8. When ever a new Opportunity is created with
stageName 'closed won' share the record
with user karthic
========================================
========================================
========
trigger opptyShareTrig on Opportunity (after insert) {
List<OpportunityShare> share=new
List<OpportunityShare>();
User u=[select id from User where alias='knair'];
for(Opportunity op:[Link]){
if([Link]=='Closed Won'){
OpportunityShare os=new
OpportunityShare();
[Link]=[Link];
[Link]=[Link];
[Link]='Edit';
[Link]='Manual';
[Link](os);
}
}
insert share;
}
Test Class :
@isTest
private class OpptyShareTest {
@isTest
static void testme(){
Opportunity op=new Opportunity();
[Link]='closed won';
[Link]=[Link]();
[Link]='Test';
try{
insert op;
}catch(Exception e){
}
user u=[select id from user where alias='knair'];
OpportunityShare share=[select
OpportunityAccessLevel,OpportunityId,RowCause,Us
erOrGroupId FROM OpportunityShare where
OpportunityId=:[Link] and UserOrGroupId=:[Link]];
if([Link]=='Closed Won'){
[Link]([Link]
sLevel,'Edit');
[Link]([Link],'Manu
al');
}else{
[Link](share,null);
}
}
}
========================================
========================================
======
9. when ever new Case is created with Priority as
'High' and origin as 'Email'
then share the record with karthic with edit
permission
========================================
========================================
======
Trigger:
trigger CaseShareTrig on Case (after insert) {
List<CaseShare> share=new List<CaseShare>();
User u=[select id from User where alias='knair'];
for(Case c:[Link]){
if([Link]=='Email' && [Link]=='High'){
CaseShare cs=new CaseShare();
[Link]=[Link];
[Link]=[Link];
[Link]='Edit';
[Link]='Manual';
[Link](cs);
}
}
insert share;
}
Test Class :
@isTest
private class CaseShareTest {
@isTest
static void testme(){
Case c=new Case();
[Link]='New';
[Link]='Email';
[Link]='High';
[Link]='Test';
try{
insert c;
}catch(Exception e){
}
User u=[select id from User where alias='knair'];
CaseShare cs=[select
CaseId,UserOrGroupId,CaseAccessLevel ,RowCaus
e from CaseShare where CaseId=:[Link] and
userOrGroupId=:[Link]];
if([Link]=='Email' && [Link]=='High'){
[Link]([Link],'Edi
t');
[Link]([Link],'Manual');
}else{
[Link](cs,null);
}
}
}
========================================
========================================
=======
10. Customer__c : Customer_share
Loan__c : Loan_Share
Candidate__c : Candidate_share
Fields :
ParentId : id of the record which we want to
share
UserOrGroupId : Id of the user / group with
whom the record need to shared
AccessLevel : Type of Access we want to
provide for the user
RowCause: Reason for sharing
Note :RowCause=Schema.CustomObject_Share.Ro
[Link]
Ex: Schema.Customer_Share.[Link]
Ex: Schema.Candidate_Share.[Link]
Example :
Object :Customer__c
Fields : Status : Approved
Rejected
Name : Text
Owd: Private
10 .When ever new customer is created with status
Approved then share the record with
user kavya with read Access
========================================
========================================
=========
trigger CustomerShare on Customer__c ( after
insert ){
List<Customer_share> share=new
List<Customer_Share>();
User u=[select id from user where
username='kavya@[Link]'];
for(Customer__c c:[Link]){
if(c.status__c='Accepted'){
Customer_Share cs=new
Customer_Share();
[Link]=[Link];
[Link]=[Link];
[Link]='Read';
[Link]=Schema.Customer_Share.RowCause.
Manual;
[Link](cs);
}
}
insert share;
}
========================================
========================================
========
[Link] ever the phone no of the account is
modified then set corresponding contacts
homephone as new Phone no of Acctount
otherPhone as Old Phone no of Account
========================================
========================================
========
class: AccountTriggerHandler :
public class AccountTriggerHandler {
public static void beforeUpdate(Map<Id,Account>
oldMap,Map<Id,Account> newMap){
List<Id> accIds=new List<Id>();
for(Id key:[Link]()){
Account old=[Link](key);
Account newAcc=[Link](key);
if([Link]!=[Link]){
[Link](key);
}
}
List<Contact> cons=[select
id,accountId,homephone,otherphone from Contact
where accountId in:accIds];
for(Contact c:cons){
Account a=[Link]([Link]);
Account b=[Link]([Link]);
[Link]=[Link];
[Link]=[Link];
}
update cons;
}
}
Trigger :
TestClass :
trigger AccountPhoneupdate on Account (before
update) {
[Link]([Link]
,[Link]);
}
@isTest
private class AccountPhoneTest {
testmethod static void testme(){
String oldPhone='111';
Account a1=new Account();
[Link]='Test';
[Link]=oldPhone;
insert a1;
Contact c1=new Contact();
[Link]=[Link];
[Link]='myla';
insert c1;
String newPhone='3445';
try{
[Link]=newPhone;
update a1;
}catch(Exception e){
}
Contact c2=[select id,otherphone,Homephone
from Contact where id=:[Link]];
if(oldPhone!=newPhone){
[Link]([Link],newPho
ne);
[Link]([Link],oldphon
e);
}else{
[Link]([Link],[Link]
phone);
[Link]([Link],[Link]
Phone);
}
}
}
========================================
========================================
========
12. Create a Following Custom Fields on Account
Object :
Field Name DataType
--------------------------------
Total_Amount Currency
PipeLine_Amount Currency
Won_Amount Currency
Lost_Amount Currency
Scenario 1: When a new Opportunity record is
created for an account rollup the opportunity amount
to Corresponding Account
1. If new Opportunity Stage is Close Won then
add the amount to Account 's
Total_Amount=Total_Amount+Opportunity
Amount
Won_Amount=Won_Amoutn+Opportuntiy
amount
2. If new Opportunity stage is closed Lost then
add the amount to Accounts
Total_Amount=Total_Amount+Opportunity
Amount
Lost_Amount=Lost_Amoutn+Opportuntiy
amount
3. If new Opportunity stage is not closed Lost or
closed won then add
the amount to Accounts
Total_Amount=Total_Amount+Opportunity
Amount
PipeLine_Amount=PipeLine_Amount+Opportuntiy
amount
Scenario 2: When a existing opportunity stage is
modified to closed won or closed lost
then
1. If stageName is modified to Closed won
Remove the amount from PipleLine_Amount
and add it to WOn_Amount
2. If StageName is modified to Closed Lost
Remove the amount from PipleLine_Amount
and add it Lost_Amount
========================================
========================================
========
Class :
public class OpptyTriggerHandler {
public static void afterInsert(List<Opportunity>
optyList){
Map<Id,List<Opportunity>> accMap=new
Map<Id,List<Opportunity>>(); // key
accountId value
for(Opportunity op:OptyList){
if([Link]([Link])){
List<Opportunity>
optList=[Link]([Link]);
[Link](op);
[Link]([Link],optList);
}else{
List<Opportunity> ops=new
List<Opportunity>{op};
[Link]([Link],ops);
}
}
List<Account> accounts=[select
id,Total_Amount__c,Won_Amount__c,Lost_Amount_
_c,
PipeLine_Amount__c from Account where
Id in:[Link]()];
for(Account a: accounts){
List<Opportunity>
oppList=[Link]([Link]);
for(Opportunity p:oppList){
a.Total_Amount__c=a.Total_Amount__c+[Link];
if([Link]=='Closed Won'){
a.Won_Amount__c=a.Won_Amount__c+[Link];
}else{
if([Link]=='Closed Lost'){
a.Lost_Amount__c=a.Lost_Amount__c+[Link];
}else{
a.pipeLine_Amount__c=a.pipeLine_Amount__c+p.a
mount;
}
}
}
}
update accounts;
}
public Static void
afterUpdate(Map<Id,Opportunity>
oldMap,Map<Id,Opportunity> newMap){
List<Opportunity> optyChanged=new
List<Opportunity>();
Map<Id,List<Opportunity>> accMap=new
Map<Id,List<Opportunity>>();
for(Id key: [Link]()){
Opportunity old=[Link](key);
Opportunity newOpp=[Link](key);
if([Link]!=[Link] ){
if(([Link]!='Closed Won' &&
[Link]!='closed Lost')&&
([Link]=='closed won' ||
[Link]=='Closed Lost')){
if([Link]([Link]
d)){
List<Opportunity>
myList=[Link]([Link]);
[Link](newOpp);
[Link]([Link],myList)
;
}else{
List<Opportunity> newList=new
List<Opportunity>();
[Link](newOpp);
[Link]([Link],newLi
st);
}
}
}
}
List<Account> accounts=[select
id,Total_Amount__c,Won_Amount__c,Lost_Amount_
_c,
PipeLine_Amount__c from Account where Id
in:[Link]()];
for(Account a: accounts){
List<Opportunity>
oppList=[Link]([Link]);
for(Opportunity p:oppList){
if([Link]=='Closed Won'){
a.Won_Amount__c=a.Won_Amount__c+[Link];
a.pipeLine_Amount__c=a.pipeLine_Amo
unt__c-[Link];
}else{
if([Link]=='Closed Lost'){
a.Lost_Amount__c=a.Lost_Amount__c+[Link];
a.pipeline_Amount__c=a.pipeLine_A
mount__c-[Link];
}
}
}
}
update accounts;
}
}
Trigger :
---------
trigger OptyRollUp on Opportunity (after insert,after
update) {
if([Link] && [Link]){
[Link]([Link]);
}
if([Link] && [Link]){
[Link]([Link]
,[Link]);
}
}
========================================
========================================
========
13 .When ever the phone field in the contact is
updated then Update the corresponding
Account records phone no as Contacts new Phone
no
========================================
========================================
========
trigger contactPhone on Conact(before update){
List<Contact> contacts=new List<Contact>();
for(Id key: [Link]()){
Contact old=[Link](key);
Contact newCon=[Link](key);
if([Link]!=[Link]){
[Link](newCon);
}
List<Account> accs=new List<Account>();
for(Contact c:contacts){
Account a=new Account();
[Link]=[Link];
[Link]=[Link];
[Link](a);
}
update accs;
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------------
Scenario 14:
Object : Lead
Evernt : before Insert
Requirement : When ever new Lead is created with
lead source as Web then assign wilson as owner
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--------------------
Triggers :
trigger OwnerAssign on Lead (before insert) {
User u=[select id from user where
username='wilson@[Link]'];
for(Lead my:[Link]){
if([Link]=='Web'){
[Link]=[Link];
}
}
}
Test Class :
@isTest
private class OwnerAssignTest {
@isTest
static void testme(){
Lead my=new Lead();
[Link]='Kiran';
[Link]='Capital';
[Link]=8000;
[Link]='Web';
insert my;
User u=[select id from User where
username='wilson@[Link]'];
Lead l=[select ownerId from Lead
where id=:[Link]];
if([Link]=='Web'){
[Link]([Link],[Link]);
}
}
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------------
Scenario 15:
Object : Account
Event : before insert
Requirement : When ever new Account is created
with Industry as 'banking' and Account Type as
'prospect'
then assign the wilson as the owner of the
record
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------
trigger AccountInsert on Account (before insert) {
User u=[select id from User where
username='wilson@[Link]'];
for(Account a:[Link]){
if([Link]=='Banking' && [Link]=='Prospect'){
[Link]=[Link];
}
}
}
@isTest
private class AccountInsertTest {
@isTest
static void testme(){
Account acc=new Account();
[Link]='Testing';
[Link]='Banking';
[Link]='Prospect';
insert acc;
User u=[select id from User where
username='wilson@[Link]'];
Account a=[select id,ownerId from Account
where id=:[Link]];
if([Link]=='Banking' &&
[Link]=='Prospect')
[Link]([Link],[Link]);
}
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----
Scenario 16:
Object : Lead
Event : before Insert
Requirement : When ever new lead is created
calcualte the lead score
Field Name Entered Blank
FirstName : 10
AnnualRevenue : 20 0
Phone : 10 0
First Create : Custom Field
Lead Score : Number(4)
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------
trigger LeadQualityTrig on Lead (before insert) {
for(Lead my:[Link]){
Integer count=0;
if([Link]!=''&&[Link]!=null)
count=count+10;
if([Link]!=null)
count=count+20;
if([Link]!='' &&[Link]!=null)
count=count+10;
my.LeadScore__c=count;
}
}
@isTest
private class LeadQualityTest {
testmethod static void testme(){
Lead my=new Lead();
[Link]='Test1';
[Link]='Kiran';
[Link]=9000;
[Link]='123';
insert my;
Lead testlead=[select id ,LeadScore__c from
Lead where id=:[Link]];
if([Link]!=null&&[Link]!=''
&&[Link]!=null && [Link]!
=''&&[Link]!=null){
[Link](testlead.leadScore__c,4
0);
}
}
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
---
Scenario : 17
Object : Opportunity
Event : After Insert
Requirement : When ever new opportunity is created
with opportuntiy Stage as closed won share the
record with
user wilson
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-------------------
trigger OptyShare on Opportunity (after insert) {
User u=[select id from user where
username='students@[Link]'];
List<OpportunityShare> share=new
List<OpportunityShare>();
for(Opportunity p:[Link]){
if([Link]=='closed won'){
OpportunityShare os=new
OpportunityShare();
[Link]=[Link];
[Link]='Read';
[Link]=[Link];
[Link]='Manual';
[Link](os);
}
}
insert share;
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------
Scenario 18:
Object : Account
Event : After Insert
Requirement : When ever new account is creatd
with Industry as Energy and AnnualRevenue more
than 20 lac
add wilson as Team memner on the Account
AccountTeamMember :
AccountId
UserId
AccountAccessLevel
TeamMemberRole
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------
Apex Class :
public class AccountTeamHandler {
public static void afterInsert(List<Account> accs){
List<AccountTeamMember> teams=new
List<AccountTeamMember>();
User u=[select id from User where
username='students@[Link]'];
for(Account a: accs){
if([Link]=='Banking' &&
[Link]>2000000){
AccountTeamMember atm=new
AccountTeamMember();
[Link]=[Link];
[Link]=[Link];
[Link]='Read';
[Link]='Account Manager';
[Link](atm);
}
}
insert teams;
}
}
Trigger:
trigger AccountTeamTrigger on Account (after insert)
{
[Link]([Link]);
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
----------------------
Scenario 19:
Object :Contact
Event : Before Update
Requirement : When ever the contacts phone
numner is ,modified ,Contact old phone number
should ne
saved as Contacts other phone
-----------------------------------------------------------------------
-----------------------------------------------------------------------
------------------
Apex Class :
public class ContactTriggerHandler {
public static void beforeUpdate(Map<Id,Contact>
oldMap,Map<Id,Contact> newMap){
List<Id> modified=new List<Id>();
for(Id key:[Link]()){
Contact old=[Link](key);
Contact newRec=[Link](key);
if([Link]!=[Link]){
[Link]=[Link];
}
}
}
}
Trigger :
trigger ContactUpdaterigger on Contact (before
update) {
[Link]([Link]
,[Link]);
}
-----------------------------------------------------------------------
-----------------------------------------------------------------------
---------------------
Scenario 20:
Create Custom Object :Course
Fields : Status : PicKList(Active,InActive)
Create Custom Object : Student
Fields : Course :Lookup(course)
Object :Course
Event : After Update
Requirement : When the status of the course is
changed to InActive then Delete all the child records
or course.
public class CourseHandler{
public static void
afterUpdate(Map<Id,Course__c>
oldMap,Map<Id,Course__c> newMap){
List<Id> courseIds=new List<Id>();
for(Id key :[Link]()){
Course__C old=[Link](key);
Course__c newCourse=[Link](key);
if(old.Status__c!='InActive' &&
newCourse.Status__c='InActive'){
[Link](key);
}
}
List<Students__c> stds=[select id from
Student__C where Course__c IN :courseIs];
delete stds;
}
}
trigger courseHandler on Course__c ( after update){
[Link]([Link],Trigger.n
ewMap);
}
==================1. Before Insert Trigger:
Object :Account
Operation :Before Insert
Scenario : When ever new account record is created
assign the owner of the
record
1. If Industry =Banking and AnnualRevenue >
50 lac
then assign to satish otherwise assign to
karthic
trigger ownerRules on Account (before insert) {
User kar=[select id from User where
username='developer@[Link]'];
User sa=[select id from User Where
Username='batch0265@[Link]'];
for(Account a: [Link]){
if([Link]=='Banking' &&
[Link]>5000000){
[Link]=[Link];
}else{
[Link]=[Link];
}
}
}
Test Class :
@isTest
private class OwerExample {
@isTest
static void testme(){
User kar=[select id from User where
username='developer@[Link]'];
User sa=[select id from User Where
Username='batch0265@[Link]'];
Account a1=new
Account(Name='Test1',Industry='Energy',AnnualReve
nue=30000);
Account a2=new
Account(Name='Test2',Industry='Banking',AnnualRev
enue=6000000);
try{
insert a1;
insert a2;
}catch(Exception e){
[Link](e);
}
Account acc1=[select id ,ownerId from Account
where id=:[Link]];
[Link]([Link],[Link]);
Account acc2=[select id,ownerId from Account
where id=:[Link]];
[Link]([Link],[Link]);
}
}
========================================
====================================
Object :Opportunity
Scenario :
When a new opportunity is created with stageName
as 'Closed Won' then this
record should be shard with user karthic with read
access ;
trigger shareExample1 on Opportunity (after insert) {
User u=[select id from User where
username='developer@[Link]'];
List<OpportunityShare> share=new
List<OpportunityShare>();
for(Opportunity op:[Link]){
if([Link]=='Closed Won'){
OpportunityShare os=new
OpportunityShare();
[Link]=[Link];
[Link]=[Link];
[Link]='Read';
[Link]='Manual';
[Link](os);
}
}
insert share;
}
========================================
=================================
Object : Account :
Scenario : When ever Account phone no is modified
udpate the corresponding
contats otherphone with modified Account's
phone no
trigger phoneUpdate on Account (before update) {
Map<Id,Account> oldMap=[Link];
Map<Id,Account> newMap=[Link];
List<Id> accIds=new List<Id>();
for(Id aid:[Link]()){
if([Link](aid).Phone!
=[Link](aid).Phone){
[Link](aid);
}
}
List<Contact> cons=new List<Contact>();
List<Account> accs=[select id,phone,(select
OtherPhone from Contacts) from Account where Id IN
:accIds];
for(Account a:accs){
for(Contact c:[Link]){
[Link]=[Link]([Link]).phone;
[Link](c);
}
}
update cons;
}
----------------
@isTest
private class PhoneTest {
testmethod static void testme(){
Account a1=new
Account(name='aaa',phone='111');
insert a1;
Contact c1=new
Contact(lastname='test',accountId=[Link]);
insert c1;
try{
[Link]='555';
update a1;
}catch(Exception e){
[Link](e);
}
Contact con=[select id ,otherphone from Contact
where accountId=:[Link]];
[Link]([Link],[Link])
;
}
}
========================================
====================================
Object : Account
Scenario :
When ever account industry field is modified to
Banking then add
karthic as accountTeam member
trigger accountTeamUpdate on Account (after
update) {
List<AccountTeamMember> team=new
List<AccountTeamMember>();
User u=[select id from user where
username='developer@[Link]'];
for(Account a:[Link]){
if([Link]=='Banking'){
AccountTeamMember atm=new
AccountTeamMember();
[Link]=[Link];
[Link]=[Link];
[Link]='Account Manager';
//[Link]='Read';
[Link](atm);
}
}
insert team;
}
======================
Trigger Class : Date 21-02-2016
========================================
========================================
=========================
Scenario :1
========================================
========================================
=========================
1. Object :Opportunity
a. When Existing Opportunity with statge name as
'Closed Won' is
updated to any other stage it has throw error
message
b. When existing Opportunity record stageName is
changed to
closed won then recalculate the Amount_Won for
the Correspondng Account (Which is a sum of all
closed
opportunities)
c. When ever the stage name is changed to Closed
and won
share that opportunity record with user 'karthic'
public class ClosedOptHandler {
public static void
beforeUpdate(Map<Id,Opportunity>
oldMap,Map<Id,Opportunity> newMap){
Set<Id> accountIds=new Set<Id>();
for(Id a:[Link]()){
Opportunity newOpt=[Link](a);
Opportunity oldOpt=[Link](a);
if([Link]=='Closed Won' &&
[Link]!='Closed Won'){
[Link]('Stage Name cannot be
updated');
}
}
}
public static void
afterUpdate(Map<Id,Opportunity>oldMap,Map<Id,Op
portunity> newMap){
Set<Id> accountIds=new Set<Id>();
for(Id a:[Link]()){
Opportunity newOpt=[Link](a);
Opportunity oldOpt=[Link](a);
if([Link]=='Closed Won'){
[Link]([Link]);
}
}
if([Link]()>0){
List<Account> accs=[select
Amount_Won__c ,(select Amount from
Opportunities where
StageName='Closed Won') from Account where Id
in:accountIds ];
Decimal sum=0;
for(Account a:accs){
for(Opportunity p:[Link]){
sum=sum+[Link];
}
a.Amount_Won__c=sum;
}
update accs;
}
}
public static void oppShare(List<Opportunity>
newOpt){
User u=[select id from User where alias='kart'];
List<OpportunityShare> share=new
List<Opportunityshare>();
for(Opportunity op: newOpt){
if([Link]=='Closed Won'){
OpportunityShare ops=new
OpportunityShare();
[Link]=[Link];
[Link]='Edit';
[Link]=[Link];
[Link]='Manual';
[Link](ops);
}
}
insert share;
}
}
----------------------------------------------------------
Trigger :
trigger closedOppty on Opportunity (after
insert,before update,after update) {
if([Link] && [Link]){
[Link]([Link]);
}
if([Link] && [Link]){
[Link]([Link]
p, [Link]);
}
if([Link] && [Link]){
[Link]([Link],
[Link]);
[Link]([Link]);
}
}
========================================
========================================
=======================
Scenario 2:
========================================
========================================
========================
Object 1: Opportunity :
Create a Custm Fields : Field Name
DataType
---------------------------------------
Total_Opportunities__c :
Number
Total_Opportunity_Amount__c :
Currency
a .When ever a new Opportunity is creatd
recalculate the total opportunites and Total
Opportunity
amount for the corresponding Account
b. When a new Opportunity is created with out
entering the account value throw error
trigger opptScope on Opportunity (before insert,
after insert) {
if([Link] && [Link]){
for(Opportunity opp=[Link]){
if([Link]==null){
[Link]('Opportuity Can not
created with out AccountId');
}
}
}
if([Link] && [Link]){
Set<Id> accId=new Set<Id>();
for(Opportunity op:[Link]){
[Link]([Link]);
}
List<Account> accounts=[select
Total_Opportunities__c,Total_Opportunity_Amount__
c,
(select id,Amount from
Opportunities) from Account where Id in:accId];
for(Account a:accounts){
a.Total_Opportunities__c=[Link]();
Decimal sum=0;
for(Opportunity p:[Link]){
sum=sum+[Link];
}
a.Total_Opportunity_Amount__c=sum;
}
update accounts;
}
}
========================================
========================================
==========================
Scenario 3:
========================================
========================================
===========================
Object : Contact
Custom Fields : Field Name DataType
----------------------------------------------
Source PickList: Sfdc
SAPExternal
Account :
Custom Fields : Field Name DataType
----------------------------------------------
Source PickList: Sfdc
SAPExternal
a. When we are trying to delete any contact
record whoes source is SAP External it should throw
error
b. When we trying to delete a contact whose
account source is SAP External it has to throw error
trigger conDeletes on Contact (before delete) {
//List<Contact> cons=[select
Source__c ,Account.Source__c from Contact where
Id in:[Link]];
for(Contact c:[Link]){
if(c.Source__c=='SAP External' ||
[Link].Source__c=='SAP External'){
[Link]('You can not delete
Conatct');
}
}
}
========================================
========================================
=====================
Scenario 4:
========================================
========================================
=====================
Object : Opportunity :
1. When ever a new Opportunity is created with
Amount more than 10 lakhs and source as 'Web'
Then add karthic as OpportunityTeamMember
Solution :
trigger optyTeam on Opportunity (after insert) {
User u=[select id from User where alias='kart'];
List<OpportunityTeamMember> teams=new
List<OpportunityTeamMember>();
for(Opportunity op:[Link]){
if([Link]> 1000000 &&
[Link]=='Web'){
OpportunityTeamMember ot=new
OpportunityTeamMember();
[Link]=[Link];
[Link]='Edit';
[Link]=[Link];
[Link]='Sales Manager';
[Link](ot);
}
}
insert teams;
}
========================================
========================================
===============================
Scenario 5:
========================================
========================================
===========================
Object : Opportunity
1. When ever the opportunity stage is changed
create dummy record in the PipeLine object with
following fieldMaping
PipleLine__c p=new PipeLine_C
[Link]=Opportunity_OldStage---
Opportunity_NewStage
[Link] =Today()-
opportunity_LastmOdifiedDate
[Link]=opportunityName
Solution :
trigger optyStageChange on Opportunity (after
update) {
List<PipeLine__c> optList=new
List<PipeLine__c>();
for(Id opId:[Link]()){
Opportunity
oldOpt=[Link](opId);
Opportunity
newOpt=[Link](opId);
if([Link]!
=[Link]){
PipeLine__c p=new PipeLine__c();
[Link]=[Link];
p.Stage__c=[Link]+'-'+[Link]
me;
Date
modDate=[Link]();
Integer
days=[Link]().daysBetween(modDate);
p.Days__C=days;
p.ConvertedDate__c=[Link]();
[Link](p);
}
}
insert optlist;
}
========================================
========================================
=============================
Scenario :6
========================================
========================================
============================
Object : Application__c
FieldName DataType Options
------------------------------------------------------
First Name Text -
Type PickList New Card
Cancel Card
Applicant PickList Business
Salaried
Status PicKList Pending
Approved
Rejected
Executive Lookup(user)
Email Email -
Object : BlackList
Field Name DataType
------------------------------------
Name Text
Object : Customer
Field Name DataType Options
-----------------------------------------------------
First Name Text
Applicatant PickList Business
Salaried
Workflow : When a new Applciation is creatd with
Type =new Card
Status=Pending
Action : Task : Assing to the Owner
Approval : When a ever a application is submitted for
Approval
Entry Criteria : Type =New Card
Automated Approved : Submited Executives
Manager
Approval steps : All Applications should enter
step 1
Approval Action : Field Update Status=
Approved
Rejected Action : Field Update Status
='Rejected'
1. When a new Application is submited for Approvel
with Application type as 'New Card'
a. check wheather Applicant name in black list
object
b. If name is in the black list object Then update
the status to Rejected
2. When applicant name is not in the black list submit
the record for approval using trigger
and set the status as pending
3. When ever the application Status is changed to
Approved
a. Create a new Customer record based on
application details
Customer FirstName =Application Firstname
Customer Type =Application -
ApplicantType
[Link] ever the application status is rejected
a. send a email to Executive ,Executive
manager, Applicant and user with role : Verification
=========================
------------------------------------------------------------------
Scenario :1
1. When ever a we are inserting a new Account
record before the
record is inserted check the industry value
a. if industry is 'Banking' set annualRevenue as
100000;
b. If industry is 'Energy' set annualRevenue as
50000
------------------------------------------------------------------
Trigger:
trigger example1 on Account (before insert) {
for(Account a: [Link]){
if([Link]=='Banking'){
[Link]=100000;
}else{
if([Link] == 'Energy'){
[Link]=50000;
}
}
}
-------------
Test Class :
-------------
@isTest
private class Example1 {
@isTest
static void testme(){
Account a1=new
Account(name='aaa',Industry='Banking');
Account a2=new
Account(name='bbb',Industry='Energy');
try{
insert a1;
insert a2;
}catch(Exception e){
[Link](e);
}
Account acc1=[select id,annualRevenue from
Account where id=:[Link]];
[Link]([Link],100
000);
Account acc2=[select id ,annualRevenue from
Account where id=:[Link]];
[Link]([Link],500
00);
}
}
------------------------------------------------------------------
Scenario 2:
1. When a new contact is created with lead source
web
2. AccountId field can not be blank or null
----------------------------------------------------------------
Trigger :
trigger example2 on Contact (before insert) {
for(Contact c:[Link]){
if([Link]=='Web' &&
([Link]==''||[Link]==null)){
[Link]('Web contact cannot be created with
out account');
}
}
}
TestClass:
----------
@isTest
private class Example2 {
@isTest
static void testme(){
Contact c1=new
Contact(lastname='satish',leadSource='web');
Contact c2=new Contact(lastname='Myla');
List<Contact> cons=new List<Contact>{c1,c2};
Integer count=[select count() from Contact];
try{
[Link](cons,false);
}catch(Exception e){
[Link](e);
}
Integer size=[select count() from contact ];
[Link](count+1,size);
}
}
-----------------------------------------------------------------------
------
Scenario 3:
1. When a new opportunity is created with following
details
[Link] is Web
[Link] > 50000
3. stagename!=closed won
2. Reassign the owner to user karthic
-----------------------------------------------------------------------
-----
trigger example3 on Opportunity (after insert) {
User u=[select id from user where alias='kart'];
List<Opportunity> ops=[select
leadsource,Amount,StageName from Opportunity
where id in:[Link]];
for(Opportunity p:ops){
if([Link]!='Closed won' && [Link]
>50000 && [Link]=='Web'){
[Link]=[Link];
}
}
update ops;
}
TestClass :
------------
@isTest
private class ExampleTest3 {
@isTest
static void testme(){
Opportunity op=new Opportunity();
[Link]='Test';
[Link]=10000;
[Link]=[Link]()+3;
[Link]='Qualification';
[Link]='Web';
try{
insert op;
}catch(Exception e){
[Link](e);
}
User u=[select id from user where alias='kart'];
Opportunity p=[select ownerid from Opportunity
where id=:[Link]];
[Link]([Link],[Link]);
}
}
-----------------------------------------------------------------------
-------
Scenario 4:
1. Calculate the Lead quality score
1. FirstName : 10 points
2. Phone :10 points
3. Email : 10 points
if the lead score is 20 then create a new contact
based on lead details
assign the owner of the lead as owner of new contact
-----------------------------------------------------------------------
----
Trigger :
trigger example5 on Lead (after insert) {
Integer total;
List<Contact> contacts=new List<Contact>();
for(Lead l:[Link]){
total=0;
if([Link]!=null && [Link]!='')
total=total+10;
if([Link]!=null && [Link]!='')
total=total+10;
if([Link]!=null && [Link]!='')
total=total+10;
if(total>=20){
Contact c=new Contact();
[Link]=[Link];
[Link]=[Link];
[Link]=[Link];
[Link]=[Link];
[Link]=[Link];
[Link](c);
}
}
insert contacts;
}
-----------------------------------------------------------------------
----
1. Deletion of account record should fail it has any
contact records
trigger example6 on Account (before delete) {
List<Account> accs=[select id,(Select id from
Contacts) from Account where Id In:[Link]];
for(Account a:accs){
if([Link]() > 0){
[Link]('Account Record with contact can
not be deleted');
}
}
}
-----------------------------------------------------------------------
------
1. Create a Custom Field No_Of_Contats on Account
Object
2. When ever new Contact is created or deleted
update the
no_of_contacts fields with no of contacts that exits
for the parent records
-----------------------------------------------------------------------
-----
Trigger
--------
trigger contactsTriggers on Contact (after insert,after
delete) {
if([Link] && [Link])
[Link]([Link]);
else
[Link]([Link]);
public class TriggerContact {
public static void increment(List<Contact> cons){
set<Id> accid=new Set<id>();
for(Contact c:cons){
[Link]([Link]);
}
List<Account> accs=[select
id,No_of_contacts__c ,(select id from Contacts ) from
Account where id in:accId];
for(Account a:accs){
a.no_of_contacts__c=[Link]();
}
update accs;
}
}
-----------------------------------------------------------------------
------