1

I am trying to update an Field when i am refreshing a detail page. I am getting this error

"Content cannot be displayed: DML currently not allowed"

VisualForce Page:

<apex:page standardController="Lead"  extensions="leadcount">
</apex:page>

Apex Code:

public with sharing class leadcount {

    public leadcount(ApexPages.StandardController controller) 
    {
            String rid=ApexPages.currentPage().getParameters().get('id');

      CountLead__c conobj=[Select id,Lead__c,CountLead__c from CountLead__c where Lead__c =:rid];


      System.debug('--------- Count Id --- '+conobj.id);
      if(conobj.CountLead__c!=null)
      {
      conobj.CountLead__c =conobj.CountLead__c +1;
      system.debug('---Lead count---'+conobj.CountLead__c);
      }      
      else
          conobj.CountLead__c = 1.0; 

      update conobj;         
    }

}

Apex-Trigger

trigger CountLead  on Lead (after insert) {

    List<CountLead__c> cntlead=new List<CountLead__c>();

    for(Lead l:Trigger.new)
    {
      cntlead.add(new CountLead__c(Lead__c=l.id, CountLead__c=0));    
    }

    try
    {
        if(cntlead.size()>0)
        {
            insert cntlead;
            System.debug('****_______------');
        }


    }
    catch (Exception e)
    {
        system.debug('---Exception----'+e.getMessage());
    }

}
2
  • Can you post the Vforce page code?
    – Ashwani
    Jun 24, 2015 at 9:00
  • @Ashwani Visualforce page contains <apex:page standardController="Lead" extensions="leadcount"> </apex:page> Jun 24, 2015 at 9:17

2 Answers 2

3

You are trying to use DML in the constructor. Move it to an separate action function in the controller and invoke it via the action attribute in your page tag

<apex:page action="{!yourActionName}">

And in your controller

public void yourActionName() {
    //your logic and DML here
} 
1
0

As a best practise , always try to include all the dml queries in a try/catch statement.In addition to that make sure you do not write DML query in Constrctr until and unless its required.

Kindly try these options and see if it works for you

3
  • @Ankita If you write DML in constructor it will throw error in runtime. So you should not write DML in constructor. Refer UweHeim answer for workaround. Jun 26, 2015 at 11:31
  • @vigneshwaranG - thats what i suggested to that guy . Jun 26, 2015 at 11:42
  • Until and unless its required means you can do. But its not Jun 26, 2015 at 11:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .