Activity Forums Salesforce® Discussions Can we use DML operation in Salesforce Apex Constructor?

  • chanchal kumar

    Member
    June 29, 2018 at 12:50 pm

    Can we use DML operations in Salesforce Apex Constructor?

  • shradha jain

    Member
    August 6, 2018 at 8:47 am

    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;

    //constructor
    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(){

    if(doDML){
    //run DML statements

    }
    return null;
    }

    }
    }

    Thanks.

  • madhulika shah

    Member
    September 19, 2018 at 12:46 pm

    Hi,

    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">

    Thanks.

  • William

    Member
    May 9, 2019 at 7:15 am

    DML operation is not allowed in the constructor of Apex class. A constructor is mainly used to initialization of variables. Salesforce has blocked this due to security issues. Whenever we go for a DML operation in the constructor it restricts us in Salesforce. Only DDL is allowed. Salesforce has blocked this due to security issues. Whenever we trying to perform any DML operations at the time of initial page load we will be ending up with an error called System.LimitException: DML currently not allowed.

    If you want to do DML operation during VF page loading, use action attribute in <apex: page>. Call a method from the action in which DML operation is allowed

Viewing 1 - 4 of 4 posts

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos