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
ckellieckellie 

Validation Rules in Apex Code

I am just finishing an apex class that drives a vf page. I have added validation rules requiring the user to either enter a value in the field "kvp_drawing__c" or the user must attach a file to the record  (code included in the same class)/. My problem is that when the user is stopped by the validation rule and corrects the record, the code will return the following error:

 

System.DmlException: Insert failed. First exception on row 0 with id a02R0000008zkXNIAY; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Error is in expression '{!save}' in component <apex:page> in page newlayoutrequest

 

 

Here is the class:

public with sharing class NewLayout {

    public NewLayout() {
    o = new Opportunity();
    currentrec = new Custom_Layout_Object__c();
    currentarec = new Attachment();
    
    }
    public boolean getmsg(){return msg;}
    public boolean getmsg2(){return msg2;}
    public class EncodingException extends Exception {}
    Apexpages.StandardController c;
    boolean msg = false;
    boolean msg2 = false;
    Public Custom_Layout_Object__c layout {get; set;}
    Public Opportunity o {get; set;}
    Public Custom_Layout_Object__c currentrec;
    Public Attachment currentarec;
    public Blob drawing {get; set;}
    public String contentType {get; set;}
    public String fileName {get; set;}
    Custom_Layout_Object__c cl = new Custom_Layout_Object__c();
    Boolean error=false;
    Integer idx=1;
    
    public NewLayout  (ApexPages.StandardController c){
            o = [select id from Opportunity where id =
                       :ApexPages.currentPage().getParameters().get('oppid')];
                system.debug('*********************000000000:'+ o);                  
         
            currentrec=(Custom_Layout_Object__c)c.getRecord(); 
            system.debug('##########currentrec:'+currentrec);

    }
    
    Public Attachment Attachment{
        get{
            if(attachment == null)
                attachment = new attachment();
             return attachment;
             }
             set;
    }

    public PageReference Cancel() {
        return null;
    }
    
    public PageReference save() {
    
    If(currentrec.KVP_or_Attachment__c == 'KVP Drawing #'){
     If(currentrec.KVP_Drawing__c== null){
      msg=true;
        } else{
    cl.Opportunity__c = o.id;
    cl.Requested_Date_to_Complete_Layout__c = currentrec.Requested_Date_to_Complete_Layout__c;
    cl.Process_Flow_Description__c = currentrec.Process_Flow_Description__c;
    cl.KVP_or_Attachment__c = currentrec.KVP_or_Attachment__c;
    cl.KVP_Drawing__c = currentrec.KVP_Drawing__c;
    cl.App_Test_has_been_requested_completed__c = currentrec.App_Test_has_been_requested_completed__c;
    cl.Quote_Request_is_in_Process__c = currentrec.Quote_Request_is_in_Process__c;
    cl.Customer_has_requested_a_layout_only__c = currentrec.Customer_has_requested_a_layout_only__c;
    cl.Customer_PO_is_pending_layout_request__c = currentrec.Customer_PO_is_pending_layout_request__c;

    insert (cl);    
    }return null;}
    If(currentrec.KVP_or_Attachment__c == 'File Attachment'){
    
     If(drawing != null){

    cl.Opportunity__c = o.id;
    cl.Requested_Date_to_Complete_Layout__c = currentrec.Requested_Date_to_Complete_Layout__c;
    cl.Process_Flow_Description__c = currentrec.Process_Flow_Description__c;
    cl.KVP_or_Attachment__c = currentrec.KVP_or_Attachment__c;
    cl.KVP_Drawing__c = currentrec.KVP_Drawing__c;
    cl.App_Test_has_been_requested_completed__c = currentrec.App_Test_has_been_requested_completed__c;
    cl.Quote_Request_is_in_Process__c = currentrec.Quote_Request_is_in_Process__c;
    cl.Customer_has_requested_a_layout_only__c = currentrec.Customer_has_requested_a_layout_only__c;
    cl.Customer_PO_is_pending_layout_request__c = currentrec.Customer_PO_is_pending_layout_request__c;

    insert (cl);    
    } else {msg2=true;
            return null;} 

    }
     if(drawing!=null){
      Attachment attach=new Attachment();
      attach.Body=drawing;
      attach.Name=filename;
      attach.ContentType=contentType;
      attach.ParentID=cl.id;
    try {
          insert(attach);
      } catch(System.DMLException e) {
          ApexPages.addMessages(e);
          return null;
      }
    }
    PageReference pageRef = new PageReference('/' + cl.id);

     return pageRef;
    }
}

 

Thank you for any advice

kriskkrisk

It is tough to debug your code as it deals with a lot of custom details that I am not aware of.

 

Since your code is producing DML exception, my 2 cents is to set up some system.debug statements to see where the logic is breaking

 

Also you can set up save points and do rollbacks to control the behavior but you may be aware that there are apex trigger limitations for Transaction control

MJ Kahn / OpFocusMJ Kahn / OpFocus

What will your code do if the insert of c1 succeeds, but the insert of the attachment fails? You catch the error and display an error message, but when your save method finishes, c1 remains inserted. That's what's causing you error message.

 

I suggest you set a Savepoint at the start of the save method, and in your catch block, roll back to the Savepoint before you return. Rolling back will essentially undo the insert, so the save method can run again when the user corrects the error and reclicks the button.

 

You might also consider using an upsert statement instead of an insert. That will also handle the situation where a record already has an id when you try to insert it.

kiranmutturukiranmutturu
cl.Opportunity__c = o.id;
cl.Requested_Date_to_Complete_Layout__c = currentrec.Requested_Date_to_Complete_Layout__c;
cl.Process_Flow_Description__c = currentrec.Process_Flow_Description__c;
cl.KVP_or_Attachment__c = currentrec.KVP_or_Attachment__c;
cl.KVP_Drawing__c = currentrec.KVP_Drawing__c;
cl.App_Test_has_been_requested_completed__c = currentrec.App_Test_has_been_requested_completed__c;
cl.Quote_Request_is_in_Process__c = currentrec.Quote_Request_is_in_Process__c;
cl.Customer_has_requested_a_layout_only__c = currentrec.Customer_has_requested_a_layout_only__c;
cl.Customer_PO_is_pending_layout_request__c = currentrec.Customer_PO_is_pending_layout_request__c;

insert (cl); // change this to upsert
ckellieckellie

Thank you and for your respective advice as both suggestions combined for the solution as you can see below:

 

public with sharing class NewLayout {

    public NewLayout() {
    o = new Opportunity();
    currentrec = new Custom_Layout_Object__c();
    currentarec = new Attachment();
    
    }
    public boolean getmsg(){return msg;}
    public boolean getmsg2(){return msg2;}
    public class EncodingException extends Exception {}
    Apexpages.StandardController c;
    boolean msg = false;
    boolean msg2 = false;
    Public Custom_Layout_Object__c layout {get; set;}
    Public Opportunity o {get; set;}
    Public Custom_Layout_Object__c currentrec;
    Public Attachment currentarec;
    public Blob drawing {get; set;}
    public String contentType {get; set;}
    public String fileName {get; set;}
    Custom_Layout_Object__c cl = new Custom_Layout_Object__c();
    Boolean error=false;
    Integer idx=1;
    
    public NewLayout  (ApexPages.StandardController c){
            o = [select id from Opportunity where id =
                       :ApexPages.currentPage().getParameters().get('oppid')];
                system.debug('*********************000000000:'+ o);                  
         
            currentrec=(Custom_Layout_Object__c)c.getRecord(); 
            system.debug('##########currentrec:'+currentrec);

    }
    
    Public Attachment Attachment{
        get{
            if(attachment == null)
                attachment = new attachment();
             return attachment;
             }
             set;
    }

    public PageReference Cancel() {
        PageReference p = new PageReference('/'+o.id);
    return p;
    }
    
    public PageReference save() {
    
    If(currentrec.KVP_or_Attachment__c == 'KVP Drawing #'){
     Savepoint sp = Database.setSavepoint();
     If(currentrec.KVP_Drawing__c== null){
      msg=true;
        } else{
    cl.Opportunity__c = o.id;
    cl.Requested_Date_to_Complete_Layout__c = currentrec.Requested_Date_to_Complete_Layout__c;
    cl.Process_Flow_Description__c = currentrec.Process_Flow_Description__c;
    cl.KVP_or_Attachment__c = currentrec.KVP_or_Attachment__c;
    cl.KVP_Drawing__c = currentrec.KVP_Drawing__c;
    cl.App_Test_has_been_requested_completed__c = currentrec.App_Test_has_been_requested_completed__c;
    cl.Quote_Request_is_in_Process__c = currentrec.Quote_Request_is_in_Process__c;
    cl.Customer_has_requested_a_layout_only__c = currentrec.Customer_has_requested_a_layout_only__c;
    cl.Customer_PO_is_pending_layout_request__c = currentrec.Customer_PO_is_pending_layout_request__c;
    try{
    upsert (cl);
    
    } catch( Exception e ){
             Database.rollback( sp );
    }
    PageReference p1 = new PageReference('/'+o.id);
    return p1;
    }}
   If(currentrec.KVP_or_Attachment__c == 'File Attachment'){
    
     If(drawing != null){

    cl.Opportunity__c = o.id;
    cl.Requested_Date_to_Complete_Layout__c = currentrec.Requested_Date_to_Complete_Layout__c;
    cl.Process_Flow_Description__c = currentrec.Process_Flow_Description__c;
    cl.KVP_or_Attachment__c = currentrec.KVP_or_Attachment__c;
    cl.KVP_Drawing__c = currentrec.KVP_Drawing__c;
    cl.App_Test_has_been_requested_completed__c = currentrec.App_Test_has_been_requested_completed__c;
    cl.Quote_Request_is_in_Process__c = currentrec.Quote_Request_is_in_Process__c;
    cl.Customer_has_requested_a_layout_only__c = currentrec.Customer_has_requested_a_layout_only__c;
    cl.Customer_PO_is_pending_layout_request__c = currentrec.Customer_PO_is_pending_layout_request__c;

    insert (cl);    
    } else {msg2=true;
            return null;} 

    }
     if(drawing!=null){
      Attachment attach=new Attachment();
      attach.Body=drawing;
      attach.Name=filename;
      attach.ContentType=contentType;
      attach.ParentID=cl.id;
    try {
          insert(attach);
      } catch(System.DMLException e) {
          ApexPages.addMessages(e);

      }
    PageReference p2 = new PageReference('/'+o.id);
    return p2;
    }
    PageReference pageRef = new PageReference('/' + cl.id);

     return null;
    }
}

 

 

Thanks.