function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDC@ChennaiSFDC@Chennai 

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 SFDC@Chennai
AshlekhAshlekh
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

All Answers

AshlekhAshlekh
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
This was selected as the best answer
SFDC@ChennaiSFDC@Chennai
<apex:page action="YOUR Funciton Name"> Working good! 
Thanks Ashlekh.
Dagny FernandesDagny Fernandes
you can not perform DML operation but there is an alternative solution by useing javascript to invoke an action.
to ensye that DML doesn't happen every time the page is refreshed i have used "initialised" boolean flag

Below is my code which may help you:
Visualforce page:
<apex:page standardController="Account" extensions="SubscriptionUpgradeController" sidebar="false">
<script>
       window.onload=function()
       {
         doInit();
       };
    </script>
<apex:form >
<apex:actionFunction name="doInit" action="{!init}" rerender="allPanel"/>
<apex:outputPanel id="allPanel">

<!-- boby-->

</apex:outputpanel>
</apex:form>
</apex:page>

apex Controller:  SubscriptionUpgradeController

public with sharing class SubscriptionUpgradeController {
public String accID {get; set;}
public String oppID {get; set;}
public Boolean initialised{get; set;}

    public SubscriptionUpgradeController(ApexPages.StandardController controller) {
        accID=ApexPages.currentPage().getParameters().get('Id');
        initialised=false;
    }

    public void init(){
	    if (!initialised){
                 Account accRec = [Select id,Name from Account where id =: accId];
			Contact conRec = [Select id,Name,AccountId from Contact Where AccountId =: accId Limit 1];
			Opportunity_Deal__c newOpportunityRec = new Opportunity_Deal__c( 
								    Name = 'Upgrade-'+accRec.Name,
								    Account_Name__c = accRec.Id,
								    Contacts__c = conRec.Id
								);
		    try{
		    	insert newOpportunityRec;
		    }catch(Exception e){
		    	
		    }
		    oppID = newOpportunityRec.Id;
		    System.debug('oppId==>'+newOpportunityRec.Id);
	    	initialised=true;
            }
     }
}


HexagonHexagon
Documentation says you should not do DML in Page Action attribute function. https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_page.htm