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
Daniel BleasdaleDaniel Bleasdale 

DML currently not allowed on Visual Force Page

I keep getting this error when I preview my Visual force page.
User-added image
Here is my custom Apex controller:-
public class PrintableView{   
public Apprentice__c ApprenticeObj{get;set;}
public Programme_Area__c ProgramArea {get;set;}
public Boolean bolPrintableView {get;set;}
        
public PrintableView(){ 
    ApprenticeObj = new Apprentice__c();
    ProgramArea = new Programme_Area__c ();
    ProgramArea.PA_Code__c = 'P12';
    insert ProgramArea;
    }
    public void init() {
 	String strPrintableView = ApexPages.currentPage().getParameters().get('print');
 	bolPrintableView = (strPrintableView == '1');
	}
	
public PageReference save(){
if(ApprenticeObj != null){
	ApprenticeObj.Programme_Area__c = ProgramArea.Id;
	ApprenticeObj.Date_of_Birth__c = date.parse('12/08/2000');
  upsert ApprenticeObj;
} 
return null;
}
}
Here is the top of my Visual force page:-
<apex:page lightningStyleSheets="True" Controller="PrintableView" title="Learning Agreement" showHeader="{!bolPrintableView}" sidebar="{!bolPrintableView}" action="{!init}">
    <apex:form >
        <apex:outputPanel rendered="{!NOT(bolPrintableView)}">
    <a href="/apex/Apprentice?print=1" target="_blank">Printable View</a>
</apex:outputPanel>

<apex:outputPanel rendered="{!bolPrintableView}">
    <script>
        window.print()
    </script>
</apex:outputPanel>

Any help is appreciated, hopefully I wont have to adjust apex because its a nighmare for me to test.

Thankyou Dan
 
Best Answer chosen by Daniel Bleasdale
Daniel BleasdaleDaniel Bleasdale
<apex:component controller="PrintableView" allowDML="true">
    
<apex:outputPanel rendered="{!NOT(bolPrintableView)}">
    <a href="/apex/Apprentice?print=1" target="_blank">Printable View</a>
</apex:outputPanel>

<apex:outputPanel rendered="{!bolPrintableView}">
    <script>
        window.print()
    </script>
</apex:outputPanel>
    
</apex:component>