• #29578

    Can we use DML operation in Salesforce Apex Constructor?

    Can we use DML operations in Salesforce Apex Constructor?



    Hello chanchal,

    No, you can’t perform any DML in Constructor because using DML in constructor will slow down initialization of your object and using insert/update/delete in constructor is a bad practice in any language.
    A quick solution would be to place the dml operations in a single method that you call from the page action parameter.

    Here is the VF page:

    <apex:page controller=”pageController” action=”{!doSomeDMLStuff}”>
    APEX Class:

    public pageController{

    private boolean doDML;

    public pageController(){

    //run some logic to decide if you need to execute dml statements

    if(logic = true){

    doDML= true;

    //the method called from the page action

    public pagereference doSomeDMLStuff(){

    //run DML statements

    return null;





    No you can’t perform any DML in Constructor.

    If you want to Perform DML then you have to write a function in class and call this functon by action attribute of <apex:page action=”YOUR Funciton Name”>


Viewing 3 posts - 1 through 3 (of 3 total)

Please to reply to this topic.


We're not around right now. But you can send us an email and we'll get back to you, asap.


About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2019 Forcetalks. All Right Reserved.

Log in with your credentials


Forgot your details?