1

We have a use case in which we wish to modify/save fields in the Lead objects from the constructor of a standard controller class.

Changing the fields goes well, but trying to modify the lead using "Standard Controller->Save()" method, or using "Upsert" fails due to "System.LimitException: DML currently not allowed"

I also tried to use @Future or schedule a job to do that change, but unfortunately @Future is not allowed in constructor and scheduling a job also fails; I can't find any trace for the job and I don't get any exceptions.

Appreciate your advice

8

You can't perform DML operations in a constructor, you can however use the VF page action function. This will allow you to perform any logic or DML operations and it is invoked before the page is rendered.

You use the action method in the tage like this

<apex:page controller="myController" action="{!myMethod}">

and in the controller

public void myMethod{
    //your logic and code here
} 

You can learn more about the Visualforce page action method here

http://www.salesforce.com/us/developer/docs/pages/index_Left.htm

3
  • 1
    Dunc44, your answer is the correct way to perform this action but your statement about the DML operations being invoked before the page is constructed is a bit misleading. Per the documentation Order of Execution for Visualforce Page Get Requests the action method defined on the page tag is executed after controller & component construction and any assignTo statements, but before the page is delivered to the browser.
    – Mark Pond
    Jul 28 '13 at 17:54
  • 1
    Mark, you are correct, I should not have used the word 'constructed' as its easy to associate that with the page constructor. You are absolutely correct though. Good catch Jul 28 '13 at 18:49
  • While this does work, please read up about CSRF and the use of 'action' and DML on page load, this does expose a security issue and will likely fail a Salesforce Security Review (if your writing packaged code for further distribution). You can read more here salesforce.com/us/developer/docs/pages/Content/… and here wiki.developerforce.com/page/… Jul 29 '13 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.