+ Start a Discussion
leduc datleduc dat 

Can't save record of child component is nested in parent component

Hi  all,
I am having an issue with saving record of lightning:recordEditForm with nested component.
I have component A which will display content depending on currentuserID. In this case, component A will call component B to open a new modal popup. The problem occurs when I press the save button, it shows a windows message like below image.
I tested component B by overriding 'new' standard action, but no errors occurred and record is saved.
So, I think component B doesn't work when nested in another component, but I don't know how to fix it properly.
I'm new to aura so I don't understand it very well.
Someone please help me. Thank you
--------------Component A( testNestedComponent.cmp)----------------------------------
<aura:component implements="lightning:actionOverride,force:hasRecordId,force:hasSObjectName">
	<!-- attributes -->
	<aura:attribute name="checkUser" type="Boolean" default="true" />
	<aura:attribute name="userId" type="User" />
	<!-- handlers-->
	<aura:handler name="init" value="{! this }" action="{! c.init }" />
	<aura:if isTrue="{!v.checkUser}">
		<lightning:listView aura:id="listViewDoctors" objectApiName="DoctorPersonalInfo__c" listName="AllDoctorPersonalInfo"
			rows="10" showSearchBar="true" showActionBar="false" enableInlineEdit="false" showRowLevelActions="false" />
	<aura:set attribute="else">
		<c:createNewDoctorPopupModal />
	</aura:set>
	</aura:if>
</aura:component>
 
-----------------Component B( createNewDoctorPopupModal.cmp)-------------------
<aura:component controller="createNewDoctor_Apex"
  implements="force:hasRecordId,flexipage:availableForAllPageTypes,lightning:actionOverride,force:lightningQuickAction">
  <lightning:workspaceAPI aura:id="workspace" />
  <aura:attribute name="loading" type="Boolean" default="false" />
  <aura:attribute name="isModalOpen" type="boolean" default="true" />

  <aura:handler name="init" value="{!this}" action="{!c.init}" />
  <div class="slds-m-around_xx-large">
    <aura:if isTrue="{!v.isModalOpen}">
      <lightning:recordEditForm objectApiName="DoctorPersonalInfo__c" aura:id="newRecordDoctorInfo"
        onsuccess="{!c.handleSuccess}" onsubmit="{!c.handleSubmit}" onerror="{!c.handleError}" onload="{!c.handleLoad}">
        <lightning:messages aura:id="OppMessage" />
        <!-- Modal/Popup Box starts here-->
        <section role="dialog" tabindex="-1" aria-hidden="false" aria-labelledby="modal-heading-01" aria-modal="true"
          aria-describedby="modal-content-id-1" class="slds-modal slds-backdrop_open">
          <div class="slds-modal__container">
            <!-- Modal/Popup Box Header Starts here-->
            <header class="slds-modal__header">
              <lightning:buttonIcon iconName="utility:close" onclick="{! c.closeModel }" alternativeText="close"
                variant="bare-inverse" class="slds-modal__close" />
              <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">{!'新規 医師情報'} </h2>
            </header>
            <!--Modal/Popup Box Body Starts here-->
            <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
              <div class="slds">
                <div class="row">

                  <div class="slds-section__title slds-theme_shade" style="padding: 3px;">
                    <h3 style="font-size: 1rem;" title="">Information</h3>
                  </div>
                  <div class="slds-grid">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large ">
                      <lightning:inputField class=".slds-size_1-of-2" fieldName="doctorName__c"
                        aura:id="newDoctorInfoField" />
                    </div>
                  </div>
                  <div class="slds-grid">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large ">
                      <lightning:inputField class=".slds-size_1-of-2" fieldName="doctorGender" aura:id="newDoctorInfoField"
                        required="true" />
                    </div>
                  </div>
				  
                </div>
              </div>
            </div>
            <!--Modal/Popup Box Footer Starts here-->
            <footer class="slds-modal__footer">
              <lightning:button variant="neutral" label="Cancel" title="Cancel" onclick="{! c.closeModel }" />
              <lightning:button variant="brand" label="Save" title="OK" type="submit" />
              <!-- onclick="{!c.submitDetails}" -->
            </footer>
          </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
        <aura:if isTrue="{!v.loading}">
          <lightning:spinner alternativeText="Loading" />
        </aura:if>
      </lightning:recordEditForm>
    </aura:if>
  </div>
</aura:component>

 
Best Answer chosen by leduc dat
Yogendra JangidYogendra Jangid
Hi Leduc, glad to hear that it's working now.
For another query that you have, actually userId is never an instance of DoctorPersonalInfo__c object but an Id only. So you can't save or insert this in your APEX class createNewDoctor_Apex. Also any call to APEX class via aura is asynchronous in nature so you may have to rewrite the record update logic once record is created.
So I would suggest you to remove this logic from APEX and aura and create a workflow rather and use workflow field update to stamp the current user ID on the custom field(User_Id__c for example) of DoctorPersonalInfo__c.
​​​​​​​Hope this answers your question. If so please can you make this as best answer. Thanks.

All Answers

leduc datleduc dat
--------------Component B( createNewDoctorPopupModalController.js))----------------------------------
({
    init: function (component, event, helper) {
        component.set('v.loading', true);
        // var userId = $A.get("$SObjectType.CurrentUser.Id");
        // alert("Hello: "+userId); 
    },
 
    handleSuccess: function (component, event, helper) {
        $A.get('e.force:showToast').setParams({
            "title": "Success",
            "message": "Record has been saved.",
            "type": "success",
        }).fire();
        // Set isModalOpen attribute to false  
        component.set("v.isModalOpen", false);
        //Close its tab 
            var workspaceAPI = component.find("workspace");
            workspaceAPI.getFocusedTabInfo().then(function(response) {
                var focusedTabId = response.tabId;
                workspaceAPI.closeTab({tabId: focusedTabId});
            })
            .catch(function(error) {
                console.log(error);
            });
    },
 
    handleError: function (component, event, helper) {
        component.set('v.loading', false);
        component.find('OppMessage').setError('ERROR----!');
    },
 
    handleLoad: function(component, event, helper) {
        component.set('v.loading', false);
    },
 
    handleSubmit: function(component, event, helper) {
        event.preventDefault();
        helper.handleFormSubmit(component);
    },
    
    closeModel: function(component, event, helper) {
        // Set isModalOpen attribute to false  
        component.set("v.isModalOpen", false);
        //Close its tab 
         var workspaceAPI = component.find("workspace");
         workspaceAPI.getFocusedTabInfo().then(function(response) {
             var focusedTabId = response.tabId;
             workspaceAPI.closeTab({tabId: focusedTabId});
         })
         .catch(function(error) {
             console.log(error);
         });
         var urlEvent = $A.get("e.force:navigateToURL");
         urlEvent.setParams({
           "url": "/lightning/page/home"
         });
         urlEvent.fire();
 
     },
})
 
--------------Component B( createNewDoctorPopupModalHelper.js))----------------------------------
({
    handleFormSubmit: function(component) {
        var showValidationError = false;
        var fields = component.find("newDoctorInfoField");
        var vaildationFailReason = '';
        //var currentDate = new Date().toJSON().slice(0,10);
 
        fields.forEach(function (field) {
            if(field.get("v.fieldName") === 'Name' && !isNaN(field.get("v.value"))){
                //alert(field.get("v.value"));
                showValidationError = true;                
                $A.get("e.force:showToast")
                .setParams({
                    type: 'error',
                    mode: 'dismissible', //sticky / pester / dismissible
                    message: 'Pleae fill in Doctor name' }).fire();  
            }
        });
         
        if (!showValidationError) {
            // var action = cmp.get("c.saveUserID");
            action.setParams({ userId : $A.get("$SObjectType.CurrentUser.Id") });
            component.set('v.loading', true);
            component.find("newRecordDoctorInfo").submit();  
        } else {
            component.find('OppMessage').setError(vaildationFailReason);
            component.set('v.loading', false); 
        }
    },
})

 
leduc datleduc dat
User-added image
Yogendra JangidYogendra Jangid
Hi Leduc
I see you are uning lightning:inputfield and there you are giving the fieldname 
<lightning:inputField class=".slds-size_1-of-2" fieldName="doctorGender" aura:id="newDoctorInfoField" required="true" />
doctorGender is not a standard field, can you please try by giving field API name here that ends with __c  and check your code then.
leduc datleduc dat
Hi Yogendra Jangid,
Thank you for answering. It's my typo mistake. 
Even i change to doctorGender__c , the error is not gone away
Yogendra JangidYogendra Jangid
ok.. I can see one more error in the code in createNewDoctorPopupModalHelper.js
// var action = cmp.get("c.saveUserID");
   action.setParams({ userId : $A.get("$SObjectType.CurrentUser.Id") });
if there is no action, don't assign any params as well. Please check and let me know if still this doesn't work.
leduc datleduc dat
@Yogendra Jangid 
Thank you, After comment out "action.setParams({ userId : $A.get("$SObjectType.CurrentUser.Id") });", it works properly.

Actually i want to save currentUserId with lightning:recordEditForm submit but it doenst work.
Can you help me see it? it's like below:

--------------Component B( createNewDoctorPopupModalHelper.js))----------------------------------
....
if (!showValidationError) {
   var action = cmp.get("c.saveUserID");
   action.setParams({ userId : $A.get("$SObjectType.CurrentUser.Id") });
   component.set('v.loading', true);
   component.find("newRecordDoctorInfo").submit();
} else {
   component.find('OppMessage').setError(vaildationFailReason);
   component.set('v.loading', false);

createNewDoctor_Apex
public with sharing class createNewDoctor_Apex {
     @AuraEnabled
     public static DoctorPersonalInfo__c saveUserID(DoctorPersonalInfo__c userId) {
         insert userId;
         return userId;
     }
}

 
Yogendra JangidYogendra Jangid
Hi Leduc, glad to hear that it's working now.
For another query that you have, actually userId is never an instance of DoctorPersonalInfo__c object but an Id only. So you can't save or insert this in your APEX class createNewDoctor_Apex. Also any call to APEX class via aura is asynchronous in nature so you may have to rewrite the record update logic once record is created.
So I would suggest you to remove this logic from APEX and aura and create a workflow rather and use workflow field update to stamp the current user ID on the custom field(User_Id__c for example) of DoctorPersonalInfo__c.
​​​​​​​Hope this answers your question. If so please can you make this as best answer. Thanks.
This was selected as the best answer