BEFORE UPDATE:
This event runs the block of code before the updated data is
committed to the database. Operations such as validation can be performed under
this event to prevent wrong entry in the database.
SYNTAX:
trigger triggerName on objectName (before update) {
// Block of code
}
SCENARIO:
We are
having the requirement to prevent status being updated to “Closed -
Converted” status on a lead object when LEAD SOURCE is null. We are going to build a trigger on
lead object to prevent status being updated to “Closed - Converted” status when LEAD
SOURCE is null.
APEX TRIGGER:
trigger leadMainTrigger on Lead (before update) { // Specifying the event.
validateLeadData obj=new
validateLeadData(); // Declaring
the instance of the class.
if(trigger.isbefore &&
trigger.isupdate) // Using
context variables.
{
obj.method1(trigger.new); //Calling apex class method.
}
}
APEX CLASS:
public class validateLeadData {
public void method1(List<Lead>
leadList){ //Getting list
of lead records from trigger.new.
for(Lead obj:leadList){ //Iterating over lead list.
if(obj.status=='Closed - Converted'
&& obj.LeadSource==''){ // checking conditions.
obj.addError('Lead status can
be updated to "Closed - Converted" status only if LEAD SOURCE is not
null '); // Throw error if the conditions are satisfied.
}
}
}
}
Now let us
update the lead status on record to "Closed
- Converted" when LEAD SOURCE is null.
how i prevent update With out putting adderror
ReplyDelete