Activity › Forums › Salesforce® Discussions › Can we use DML operation in Salesforce Apex Constructor?
Tagged: Apex Constructor in Salesforce, Constructor, Constructor in Apex, DML Exception, DML in Salesforce, DML Operations, Salesforce Apex Class
-
Can we use DML operation in Salesforce Apex Constructor?
Posted by chanchal kumar on June 29, 2018 at 12:50 PMCan we use DML operations in Salesforce Apex Constructor?
William replied 7 years ago 4 Members · 3 Replies -
3 Replies
-
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.
- [adinserter block='9']
-
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.
-
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
Log In to reply.