0

I have a requirement where user should be able to create Parent and child record with single button click on one page. For this I created 2 lightning-record-edit-form on the LWC, but unable to find a way to pass the Parent Id to Child record form on submit. Can any one suggest some ideas on how to acheive it? In the below picture first 2 fields come from Parent and second 2 from child. On save both records should be saved, Child should be related to the Parent. I am using 2 forms because, child fields might vary based on the record type of parent.

LWC:

<template>
        <div class="modal-body">
            <br />
            <lightning-card>
                <lightning-record-edit-form
                    record-id={recordId}
                    object-api-name="ParentObject__c"
                    record-type-id={parentId}
                    onsuccess={handleSuccess}
                    onsubmit={handleSubmit}
                    onerror={handleError}
                                        >
                    <lightning-messages> </lightning-messages>
                    
                    <template>
                        <div class="slds-grid slds-wrap">
                            <!-- <template if:true={fields}>-->
                            <template for:each={parentfields} for:item="f">
                                <div key={f.Id} class="slds-col slds-size_1-of-2">
                                    <lightning-input-field field-name={f.APIName}> </lightning-input-field>
                                </div>
                            </template>
                            <!--</template>-->
                        </div>
                    </template>
                </lightning-record-edit-form></lightning-card
            >
            <template>
                <template>
                    <lightning-card title="Account/Site-Specific Fields">
                        <lightning-record-edit-form
                            record-id={recordId}
                            object-api-name="childObject__c"
                            onsuccess={handleSuccess}
                            onsubmit={handleSubmit}
                            onerror={handleError}
                        >
                            <div class="slds-grid slds-wrap">
                                <!-- <template if:true={fields}>-->
                                <template for:each={childfields} for:item="f">
                                    <div key={f.Id} class="slds-col slds-size_1-of-2">
                                        <lightning-input-field field-name={f.APIName}> </lightning-input-field>
                                    </div>
                                </template>
                                <!--</template>-->
                            </div>
                        </lightning-record-edit-form></lightning-card
                    ></template
                >
            </template>


            <br />
        </div>
        <div slot="footer">
            <template>
            <lightning-button class="slds-m-top_small slds-p-right_medium" variant="brand" onclick={handleSubmit} name="save" label="Save"> </lightning-button
            ></template>
        </div>
    
</template>

JS:

import { LightningElement, track, api } from 'lwc';
import CreationChild from '@salesforce/apex/CreationController.CreationChild';
import getForm from '@salesforce/apex/CreationController.getForm';
import getRecordTypeId from '@salesforce/apex/CreationController.getRecordTypeId';
import getRecordTypeDevName from '@salesforce/apex/CreationController.getRecordTypeDevName';
import { RefreshEvent } from 'lightning/refresh';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
export default class CreationLwc extends NavigationMixin(LightningElement) {
    DisplayText = false;
    @api size;
    @api objectName;
    @api recordId;
    @api fieldSet;
    @track fields;
    @track systemfields;
    @track isModalOpen = false;
    @api PortfolioRecordTypeName;
    @api PortfolioRecordTypeId;
    @api PortfolioRecordTypeDevName = 'Test';
    @api accrecordId;
    @api showOFields = false;
    @api showTFields = false;
    @api portAccountId;
    @api selectedPortfolioId;
    @api showPortfolio = false;
    isLoading = false;
    @api isSystemFields = false;
    account;
    

    openModal() {
        this.isModalOpen = true;
    }
    closeModal() {
        this.isModalOpen = false;
        this.dispatchEvent(new RefreshEvent());
    }
    submitDetails() {
        this.isModalOpen = false;
    }
    handleSuccess(event) {
        console.log('onsubmit event recordEditForm' + event.detail.id);
                this.createRelationship( event.detail.id, this.accrecordId, 'Owner');
                this.navigateToRecordPage();
    }
   
    handleOTChange(event) {
        console.log('You selected an account: ' + event.detail.value);
        if (event.detail.value === 'Owner') {
                        this.getFieldsForOwner();
                        this.getFieldsForChild();
            this.showOFields = true;
            this.showTFields = false;
            this.showPortfolio = false;
            //this.connectedCallback();
        } 
        } else if (event.detail.value === '') {
            this.showOFields = false;
            this.showTFields = false;
        }
    }
    
    getFieldsForOwner() {
        //this.template.querySelector('c-modal').show();
        getForm({ recordId: this.recordId, objectName: 'parent__c', fieldSetName: this.PortfolioRecordTypeDevName })
            .then(result => {
                console.log('Data:' + JSON.stringify(result));
                if (result) {
                    this.fields = result.Fields;
                    this.error = undefined;
                }
            })
            .catch(error => {
                console.log(error);
                this.error = error;
            });
    }
    
    validateFields() {
        return [...this.template.querySelectorAll('lightning-input-field')].reduce((validSoFar, field) => {
            return validSoFar && field.reportValidity();
        }, true);
    }
  
        handleSubmit(e){
        
                const inputFields = e.detail.fields;
                this.template.querySelector('lightning-record-edit-form').submit(inputFields);  
        
        
        }
    handleError(e) {
        //this.template.querySelector('[data-id="message"]').setError(e.detail.detail);
        e.preventDefault();
    }

       
    closeComponent() {
        const close = new CustomEvent('close');
        this.dispatchEvent(close);
    }
        navigateToRecordPage() {
        this[NavigationMixin.Navigate]({
            type: "standard__recordPage",
            attributes: {
              actionName: "view",
              recordId: this.accrecordId
            }
          });
}
         handleEmpty(event) {
        this.account = event.detail;
    }
         getFieldsForChild() {
        
        getForm({ recordId: this.recordId, objectName: 'child__c', fieldSetName: this.PortfolioRecordTypeDevName })
            .then(result => {
                console.log('Data:system fields' + JSON.stringify(result));
                if (result) {
                    this.systemfields = result.Fields;
                                        this.isSystemFields = true;
                    this.error = undefined;
                }
            })
            .catch(error => {
                console.log(error);
                this.error = error;
            });
    }
}
2
  • Can you share your javascript code as well, would like to see the event handler methods
    – prem22
    Jul 31, 2023 at 7:57
  • @prem22 added js
    – Anjali
    Jul 31, 2023 at 15:28

1 Answer 1

2
+50

I would add an identifier on both form, e.g. data-id="parent" and data-id="child", in order to query the right one.
Moreover I would remove onsubmit={handleSubmit} on both form since they are not being called. What runs is the one on the Save button, therefore you can change the handleSubmit code to:

handleSubmit() {
    this.template.querySelector('lightning-record-edit-form[data-id="parent"]').submit();
}

I would import the lookup field to use it later:

import LOOKUP_TO_PARENT_FIELD from '@salesforce/schema/ChildObject__c.Parent__c';

I would also have two differents handlers for the onsuccess event, e.g. onsuccess={handleSuccessParent} and onsuccess={handleSuccessChild}.
In handleSuccessParent method you should store the id of the parent object, the build the object with every child field, in order to pass it to the submit method.
Since you didn't add the createRelationship method to the question, I'm going to assume that accrecordId holds the Id of the parent record.

handleSuccessParent(event) {
    const parentId = event.detail.id;
    this.accrecordId = parentId;
    const inputFields = {};
    inputFields[LOOKUP_TO_PARENT_FIELD.fieldApiName] = parentId;
    const childInputFields = this.template.querySelectorAll('lightning-record-edit-form[data-id="child"] lightning-input-field');
    for (const field of childInputFields) {
        if (field.value) {
            inputFields[field.fieldName] = field.value;
        }
    }
    console.log('inputFields', inputFields);
    this.template.querySelector('lightning-record-edit-form[data-id="child"]').submit(inputFields);
}

In handleSuccessParent method you could navigate to the record page as you did in your handleSuccess method:

handleSuccessChild() {
    this.navigateToRecordPage();
}

The HTML should look like:

<template>
    <div class="modal-body">
        <br />

        <lightning-card>
            <lightning-record-edit-form
                record-id={recordId}
                object-api-name="ParentObject__c"
                data-id="parent"
                record-type-id={parentId}
                onsuccess={handleSuccessParent}
                onerror={handleError}>
                <lightning-messages> </lightning-messages>
                
                <template>
                    <div class="slds-grid slds-wrap">
                        <!-- <template if:true={fields}>-->
                        <template for:each={parentfields} for:item="f">
                            <div key={f.Id} class="slds-col slds-size_1-of-2">
                                <lightning-input-field field-name={f.APIName}> </lightning-input-field>
                            </div>
                        </template>
                        <!--</template>-->
                    </div>
                </template>
            </lightning-record-edit-form>
        </lightning-card>

        <template>
            <lightning-card title="Account/Site-Specific Fields">
                <lightning-record-edit-form
                    record-id={recordId}
                    object-api-name="childObject__c"
                    data-id="child"
                    onsuccess={handleSuccessChild}
                    onerror={handleError}>
                    <div class="slds-grid slds-wrap">
                        <!-- <template if:true={fields}>-->
                        <template for:each={childfields} for:item="f">
                            <div key={f.Id} class="slds-col slds-size_1-of-2">
                                <lightning-input-field field-name={f.APIName}> </lightning-input-field>
                            </div>
                        </template>
                        <!--</template>-->
                    </div>
                </lightning-record-edit-form>
            </lightning-card>
        </template>

        <br/>
    </div>

    <div slot="footer">
        <lightning-button class="slds-m-top_small slds-p-right_medium" variant="brand" onclick={handleSubmit} name="save" label="Save"> </lightning-button>
    </div>

</template>
0

You must log in to answer this question.

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