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
Carolyn juliana 7Carolyn juliana 7 

How to fix Apex DML Exception while Record Save from Lightning

Dear Gurus,

This is about a Apex DML exception which is troubling
23:43:49:014 EXCEPTION_THROWN [49]|System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Level 1, Case]: [Level 1, Case]

Here is apex code-->
public class PickListHandler {
    @AuraEnabled
    public static List<String> getLevel1(){
    List<String> tempLst1 = new List<String>();
        for(AggregateResult  ar : [select Level_1__c,COUNT(id) from Case_Type_Data__c  group by Level_1__c])
    {
        tempLst1.add(''+ar.get('Level_1__c'));
    }

    return tempLst1;
      
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel2(string strName){
    List<String> tempLst2 = new List<String>();
       for(AggregateResult  ar : [select Level_2__c,COUNT(id) from Case_Type_Data__c where Level_1__c=:strName  group by Level_2__c])
    {
       tempLst2.add(''+ar.get('Level_2__c'));
    }

    return tempLst2;
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel3(string strName1,string strName2){
     List<String> tempLst3 = new List<String>();
      for(AggregateResult  ar : [select Level_3__c,COUNT(id) from Case_Type_Data__c  where Level_1__c=:strName1 and Level_2__c=:strName2 group by Level_3__c])
    {
       tempLst3.add(''+ar.get('Level_3__c'));
    }

    return tempLst3;
      
      
    } 
         
     @AuraEnabled
     public  static String  savecasetype(string level1,string level2,string level3,string caseid){
     string strMsg='successfull';
          try{
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Case__c =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     Return 'Successfully Inserted Levels';
     }
     
    catch(Exception ex){
            strMsg='error';
        }
     return strMsg;  
}
    
     
    
    

}

Hereis working Test class for above apex-->
@isTest
public class testGetAllLevels { 

static testMethod void testGetLevel1()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel1();

}
    
static testMethod void testGetLevel2()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel2('Test Level 1');

}
    
static testMethod void testGetLevel3()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    obj.Level_2__c = 'Test Level 2';
    obj.Level_3__c = 'Test Level 3';
    insert obj;
    List<String> s = PickListHandler.getLevel3('Test Level 1','Test Level 2');

}
    
    
static testMethod void testsaveCaseType(){
        // Create the Case Record.
        Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); 
        insert cas;
       
        ERT_Case_Type__c obj=new ERT_Case_Type__c();
        string one='one';
        string two='two';
        string three='three';
        test.startTest();
        String testing=PickListHandler.savecasetype(one,two,three,cas.id);
        test.stopTest();
    }
    

    
 
    
}

Here is lightning component JS -->
({
    doInit : function(component, event, helper) {
        var action = component.get("c.getLevel1");
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                component.set("v.lstLevel1",result);
            }
        });
        $A.enqueueAction(action);
    },    
    getLvl1:function(component, event, helper){
       
        var picklist=component.find('ddLevel1');
        var picklistvalue=picklist.get('v.value');
        var action = component.get("c.getLevel2");
        //alert('called'+picklistvalue);
        action.setParams({  'strName' : picklistvalue  });//
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                component.set("v.lstLevel2",result);
            }
        });
        $A.enqueueAction(action);
        //  alert(picklistvalue);
    },
    getSelectedValue:function(component, event, helper){
        var picklist=component.find('ddLevel1');
        var picklistvalue=picklist.get('v.value');
        var picklistdep=component.find('ddLevel2');
        var picklistvaluedep2=picklistdep.get('v.value');
        var action = component.get("c.getLevel3");
       // alert(picklistvaluedep2+' called'+picklistvalue);
        action.setParams({  'strName1' : picklistvalue,
                         'strName2' : picklistvaluedep2});//
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                component.set("v.lstL3",result);
            }
        });
        $A.enqueueAction(action);
       // alert(picklistvalue+'  '+picklistvaluedep);
    },
    onConfirm:function(component, event, helper){
        var picklist=component.find('ddLevel1');
        var picklistvalue=picklist.get('v.value');
        var picklistdep=component.find('ddLevel2');
        var picklistvaluedep2=picklistdep.get('v.value');
       
        var picklistdep3=component.find('ddLevel3');
        var picklistvaluedep3=picklistdep3.get('v.value');
        var action = component.get("c.savecasetype");
        
        action.setParams({  'strName1' : picklistvalue,
                          'strName2' : picklistvaluedep2,
                          'strName3' : picklistvaluedep3,
                          'id' : component.get("v.recordId")});//
                          
        
        var toastEvent = $A.get("e.force:showToast");
       //alert('abcd');
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                // alert(result);
                if(result==='successfull'){
                    toastEvent.setParams({
                        "title": "Success!",
                        "message": "The record has been inserted  successfully."
                    });
                    toastEvent.fire();
                }else{
                    toastEvent.setParams({
                        "title": "Error",
                        "message": "The record has not been inserted  successfully."
                    });
                    toastEvent.fire();
                }
            }
        });
        $A.enqueueAction(action);
       
    }
})

Here is Apex handler -->
<aura:component controller="PickListHandler" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <!-- Actions-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <!-- variable-->
    <aura:attribute name="lstLevel1" type="String[]" />
     <aura:attribute name="lstLevel2" type="String[]" />
      <aura:attribute name="lstL3" type="String[]" />
    <span> Level 1</span>
    <ui:inputSelect aura:id="ddLevel1" change="{!c.getLvl1}">
        <ui:inputSelectOption label="-Select-" value="true"/>        
        <aura:iteration items="{!v.lstLevel1}" var="value">          
            <ui:inputSelectOption label="{!value}" text="{!value}" />
        </aura:iteration>
    </ui:inputSelect>
    <span>Level 2</span>
    <ui:inputSelect aura:id="ddLevel2" change="{!c.getSelectedValue}">
        <ui:inputSelectOption label="-Select-" value="true"/>        
        <aura:iteration items="{!v.lstLevel2}" var="value">          
            <ui:inputSelectOption label="{!value}" text="{!value}" />
        </aura:iteration>
    </ui:inputSelect>
     <span>Level 3</span>
    <ui:inputSelect aura:id="ddLevel3" >
        <ui:inputSelectOption label="-Select-" value="true"/>        
        <aura:iteration items="{!v.lstL3}" var="value">          
            <ui:inputSelectOption label="{!value}" text="{!value}" />
        </aura:iteration>
    </ui:inputSelect>
    <lightning:button variant="brand" label="Save" onclick="{!c.onConfirm}" />
</aura:component>
Now when i run test class basically create a case and pass the id to apex class,i see no issues but issue comes only when i click 'Save',i see ""The record has not been inserted successfully."" On checking Logs i found DML exception as below
23:43:49:014 EXCEPTION_THROWN [49]|System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Level 1, Case]: [Level 1, Case]

Please note in this scenarion Each case can have multiple ERT_Case_Type__c and each ERT_Case_Type__c can have multiple Case_Type_Data__c

Please help in finding  resolution.

Thanks in Advance
Carolyn
 
Best Answer chosen by Carolyn juliana 7
AnudeepAnudeep (Salesforce Developers) 
Hi Carolyn, 

Are you missing populating any required fields on ERT_Case_Type__c object?

The issue appears to be coming from the below method. Can you try invoking this method from execute anonymous window and see if you can reproduce the issue?
 
@AuraEnabled
     public  static String  savecasetype(string level1,string level2,string level3,string caseid){
     string strMsg='successfull';
          try{
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Case__c =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     Return 'Successfully Inserted Levels';
     }

Anudeep

All Answers

AnudeepAnudeep (Salesforce Developers) 
Hi Carolyn, 

Are you missing populating any required fields on ERT_Case_Type__c object?

The issue appears to be coming from the below method. Can you try invoking this method from execute anonymous window and see if you can reproduce the issue?
 
@AuraEnabled
     public  static String  savecasetype(string level1,string level2,string level3,string caseid){
     string strMsg='successfull';
          try{
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Case__c =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     Return 'Successfully Inserted Levels';
     }

Anudeep
This was selected as the best answer
Carolyn juliana 7Carolyn juliana 7
thanks anudeep,just added a  debug statement and tried to pass id i apex still am getiing null in Case__c as below
  
08:22:45:002 USER_DEBUG [46]|DEBUG|CASE  = null
Here is updated apex 
@AuraEnabled
     public  static String  savecasetype(string level1,string level2,string level3,string id){
     string strMsg='successfull';
          try{
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Case__c = id;
     System.debug('CASE  = '+ Obj.Case__c); 
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
  
     }
     
    catch(Exception ex){
            strMsg='error';
        }
     return strMsg;  
}
Carolyn juliana 7Carolyn juliana 7
How do i make sure instead of null i can pass the Caseid from onconfirm function
Andrew GAndrew G
Hi Carolyn

The question i would ask is how are you invoking the code to get the error?
Reading the class and the test class, it reads Ok.
I have created an object in a dev org, done a similar piece of code with a test class.  Invoking the test class gives the Case and therefore the CaseId.  If the test class runs the code without error, and you are getting the error when running it in the "live" environment, then you would need to check how the code is being invoked at that time.  Are you trying to run the Lightning component and getting the error?

Regards
Andrew