4

If you update name of record in both before insert trigger and save method of custom controller.Which one will get updated.I went through this example provided by salesforce.I am getting confused.Can someone explain me the execution order in visualforce page

2 Answers 2

1

Your triggers will be fired as soon as you use a DML operation in your trigger.

Take this very simple example:

Visualforce

<apex:page controller="CustomController">
    <apex:commandButton action="{!saveObject}" value="Save"/>
</apex:page>

Custom Controller

public class CustomController
{
    public PageRefence saveObject()
    {
        CustomObject__c anObject = new CustomObject__c();
        anObject.CustomField__c = 'Cheese';
        insert anObject;

        return null;
    }
}

Trigger

trigger CustomObjectTrigger on CustomObject__c (before insert) 
{
    for(CustomObject anObject : Trigger.new)
    {
        anObject.CustomField__c = 'Bacon';
    }
}

In this case the CustomObject__c record that has been created will have 'Bacon' in CustomField__c NOT 'Cheese' as it was overwritten by the trigger.

If you don't want this behavior then you can add a checkbox to your object and then check if it is checked or not in your trigger to allow you to bypass it.

Here is an example:

Custom Controller

public class CustomController
{
    public PageRefence saveLead()
    {
        CustomObject__c anObject = new CustomObject__c();
        anObject.CustomField__c = 'Cheese';
        anObject.AllowAutoUpdate__c = false;
        insert anObject;

        return null;
    }
}

Trigger

trigger CustomObjectTrigger on CustomObject__c (before insert) 
{
    for(CustomObject anObject : Trigger.new)
    {
        if(anObject.AllowAutoUpdate__c)
        {
            anObject.CustomField__c = 'Bacon';
        }
    }
}

In this case the CustomObject__c record that has been created will have 'Cheese' in CustomField__c as it was not overwritten by the trigger since AllowAutoUpdate__c was false.

0

The example you looked at explained that order of execution on the visualforce page can't be guaranteed if your code is written in certain ways. The record itself doesn't get updated until you save when using a before insert trigger.

You must log in to answer this question.

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