+ Start a Discussion
vikas  malikvikas malik 

Can we do DML operation in constructor

Hi- I just want to delete the existing records in contructor itself. 
This code is working in action method but its not working in constructor, Please share me idea if any one have. 

List<Forecast_Revenue_Report__c> foreRevRepOutput = [SELECT Forecast_Amount__c, Forecast_Month__c, opp_id__c FROM Forecast_Revenue_Report__c WHERE opp_id__c = :this.oppId];
for(Forecast_Revenue_Report__c frDelete : foreRevRepOutput ) {
                    delete frDelete;
       }

Thanks,
Best Answer chosen by vikas malik
Gaurav NirwalGaurav Nirwal

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

There are some blog 

http://salesforceworld4u.blogspot.in/2014/08/how-to-do-dml-operation-when-page-loads.html

http://www.mindfiresolutions.com/DML-Operation-Salesforce-ApexA-Trick-To-Avoid-Problem-Of-DML-At-Constructor-1809.php