+ Start a Discussion
ifthikar ahmedifthikar ahmed 

Hi All, i am very new to Salesforce and just started learning.. i am following trial head for Developer 1 and trying to experiment with triggers...

my trigger is for the Lead , PFB for the Trigger

trigger HelloWorld on Lead (before update) {
    for (Lead l : Trigger.new){
        l.FirstName = 'Hello';
        l.LastName = 'World';
    }
once after saving this when i go to lead and just select the record. immediately the f.name and l.name is getting changed to Hello world.... i have not even done any changes more over didnt click on the save button also..

To my understanding trigger shuld execute only if i make any change in the record or even while just viewing the record by clicking on its name itself will the trigger gets executed as it is a before trigger
Ajay K DubediAjay K Dubedi
Hi ifthikar,
Generally, trigger fires when an event occurred on particular object(Below snippet is for Lead). To handle the trigger execution must use context variable for best practices. As per your requirement, I had tested below trigger in my org it is working fine.
Use the below code:
//Trigger Code
trigger triggerOnLead on Lead (before update) {
    if(trigger.isUpdate && trigger.isBefore){
       ChangeNameLead.ChangeNameLead_method(Trigger.new);
    }
}

//Helper code
public class ChangeNameLead {
    public static void ChangeNameLead_method(List<Lead> leadList){
        for (Lead leadObj : leadList){
            leadObj.FirstName = 'Hello';
            leadObj.LastName = 'World';
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi