1

can you give me the examples of above triggger events(before insert,before update).How to solve above scenario's please give some ideas.

2
  • 2
    This is a very open question, what specifically are you trying to achieve? What have you tried?
    – Girbot
    Commented Jul 9, 2015 at 7:17
  • i had tried so far not executing give one example on that
    – salesforce
    Commented Jul 9, 2015 at 7:19

2 Answers 2

2

You have asked for example, therefore:

Example Triggers:

trigger AccountTrigger on Account (before insert)
{
    Contact cont = new Contact();
    cont.LastName = Trigger.new[0].name;
    cont.FirstName = Trigger.new[0].name;
    insert cont;
}

trigger AccountTrigger on Account (before update)
{
    Contact cont = new Contact();
    cont.LastName = '(Updated)';
    cont.FirstName = Trigger.new[0].name+ 'Updated';
    insert cont;
}

As a best practice we combine them into one trigger as:

trigger AccountTrigger on Account (before insert, before update)
{
    if(Trigger.isBefore)
    {
        if(Trigger.IsInsert)
        {
            Contact cont = new Contact();
            cont.LastName = Trigger.new[0].name;
            cont.FirstName = Trigger.new[0].name;
            insert cont;
        }
        else if(Trigger.IsUpdate)
        {
            Contact cont = new Contact();
            cont.LastName = '(Updated)';
            cont.FirstName = Trigger.new[0].name+ 'Updated';
            insert cont;
        }
    }
}

Now, What is Trigger, Trigger.new[0] etc.?

Trigger.New is a context variable. which returns a list of new records of the Sobjects which will be inserted into the database (if everything goes well). You can read all about them here .

1

I was just studying triggers, and I am thinking you might be wondering use cases to use before and after triggers.

Before triggers can be used when you want to make a change to a record in the trigger context variable trigger.new, and not have to use a DML statement to save your changes. You can edit them in the trigger and once the record commits to the database your new values will be on the record.

After triggers would be used for post-commit logic like updating related records, sending emails, etc.

I hope this helps..

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .