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
Raju SudheerRaju Sudheer 

can we write DML operation in a constructer?

bob_buzzardbob_buzzard
It depends on what context the constructor is being called. You can do this in a constructor of a regular Apex class, but not for the constructor of a Visualforce controller. This is a security feature as simply executing a GET on a page should not have side effects, and carrying out DML is considered a side effect.
RAJNagRAJNag
Hi Raju

Constructor is mainly used to initialization of variables. It is not used for doing DML operations.
Salesforce has blocked this due to security issues.
If you want to do DML operation during VF page loading, use action attrirbute in <apex:page>. Call a method from the action in which DML operation is allowed.

You need more information please refer below links

http://salesforce.stackexchange.com/questions/28833/why-is-dml-not-allowed-in-constructor
https://developer.salesforce.com/forums/?id=906F00000008zoZIAQ
http://th3silverlining.com/2009/11/23/dml-currently-not-allowed/


Thanks
Raj
 
bob_buzzardbob_buzzard
You shouldn't carry out DML in a page action call if that page does anything other than forward to another page. This is because there is no guaranteed order so if other methods in your controller rely on the DML operation happening first, this may not be the case.

The cleanest workaround I've found for this is to use JavaScript:

http://bobbuzzard.blogspot.co.uk/2011/08/dml-during-initialisation.html

This would fail the security review if you are building an app exchange package though, as its still essentially a DML side effect of carrying out a GET.