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
The new LearnerThe new Learner 

parentid is not coming while creating new child record in lwc

HI Experts,

My below code is working fine, however, while creating a new child record, parentid is not populating automatically, again I am selecting to add that child record to parent, can anyone help me out. For example, in the account record related list if we create contact record automatically that specific accountid(name) will come on the record detail page of contact. Same functionality I need in my below component. can anyone help me out?
 
TEmpate:

<template>
<lightning-card title={titleWithCount} icon-name="standard:record">
    <lightning-button label="New" slot="actions" onclick={createNew}></lightning-button>
    <div slot="footer">
        <div  if:true={countBool}>
            <lightning-button label="View All" onclick={navigateToRelatedList}></lightning-button>
        </div>
    </div> 
    <div class="slds-m-around_medium">   
        <div if:true={listRecords}>   
            <template for:each={listRecords} for:item="rec">    
                <div key={rec.Id} class="slds-box">                         
                    <lightning-record-view-form record-id={rec.id} object-api-name={objectName}>
                        <div class="slds-grid">
                            <div class="slds-col slds-size_1-of-2">
                                <lightning-output-field field-name={field1}></lightning-output-field>
                                <lightning-output-field field-name={field2}></lightning-output-field>
                            </div>
                            <div class="slds-col slds-size_1-of-2">
                                <lightning-output-field field-name={field3}></lightning-output-field>
                                <lightning-output-field field-name={field4}></lightning-output-field>
                            </div>
                        </div>
                    </lightning-record-view-form><br/><br/>
                </div>                       
            </template>   
        </div>   
    </div>   
</lightning-card>       
</template>


JS:

import { LightningElement, api, wire, track } from 'lwc'; 
import fetchRecords from '@salesforce/apex/RelatedListController.fetchRecords'; 
import { NavigationMixin } from 'lightning/navigation';
 
export default class RelatedList extends NavigationMixin( LightningElement ) { 
 
    @api objectName; 
    @api parentObjectName;
    @api fieldName; 
    @api fieldValue; 
    @api parentFieldAPIName; 
    @api recordId; 
    @api strTitle; 
    @api filterType; 
    @api operator; 
    @api fieldsList;
    @api relationshipApiName;
    @track field1;
    @track field2;
    @track field3;
    @track field4;
    @track listRecords;
    @track titleWithCount;
    @track countBool = false;
    //@api recordid;

    connectedCallback() {

        var listFields = this.fieldsList.split( ',' );
        console.log( 'Fields are ' + listFields );
        this.field1 = listFields[ 0 ].trim();
        this.field2 = listFields[ 1 ].trim();
        this.field3 = listFields[ 2 ].trim();
        this.field4 = listFields[ 3 ].trim();
        console.log( 'Field 1 is ' + this.field1 );
        console.log( 'Field 2 is ' + this.field2 );
        console.log( 'Field 3 is ' + this.field3 );
        console.log( 'Field 4 is ' + this.field4 );

    }

    get vals() { 

        return this.recordId + '-' + this.objectName + '-' +  
               this.parentFieldAPIName + '-' + this.fieldName + '-' +  
               this.fieldValue + '-' + this.filterType + '-' + this.operator + '-' + this.fieldsList; 

    } 
     
    @wire(fetchRecords, { listValues: '$vals' }) 
    accountData( { error, data } ) {

        if ( data ) {
          
            this.listRecords = data.listRecords;
            console.log(JSON.stringify(this.listRecords));
            if ( data.recordCount ) {
               
                if ( data.recordCount > 3 ) {

                    this.titleWithCount = this.strTitle + '(3+)';
                    this.countBool = true;
               
                } else {

                    this.countBool = false;
                    this.titleWithCount = this.strTitle + '(' + data.recordCount + ')';

                }
            }

        }

    }

    createNew() {

        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: this.objectName,
                actionName: 'new'
            }
        });

    }

    navigateToRelatedList() {
       
        this[NavigationMixin.Navigate]({
            type: 'standard__recordRelationshipPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: this.parentObjectName,
                relationshipApiName: this.relationshipApiName,
                actionName: 'view'
            }
        });

    }
 
}

Meta:

<?xml version="1.0" encoding="UTF-8"?> 
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="RelatedList"> 
    <apiVersion>52.0</apiVersion> 
    <isExposed>true</isExposed> 
    <targets> 
        <target>lightning__RecordPage</target> 
    </targets> 
    <targetConfigs> 
        <targetConfig targets="lightning__RecordPage"> 
            <property name="strTitle" type="String" label="Title" description="Enter the title"/> 
            <property name="objectName" type="String" label="Object Name" description="Enter the object name"/> 
            <property name="parentObjectName" type="String" label="Parent Object Name" description="Enter the parent object name"/> 
            <property name="relationshipApiName" type="String" label="Relationship Name" description="Enter the relationship API name"/> 
            <property name="parentFieldAPIName" type="String" label="Parent Field API Name" description="Enter the parent field API Name"/> 
            <property name="fieldName" type="String" label="Field Name" description="Enter the field name"/> 
            <property name="fieldValue" type="String" label="Field Value" description="Enter the field value"/> 
            <property name="filterType" type="String" label="Filter Type" description="Enter the filter type"/> 
            <property name="operator" type="String" label="Operator" description="Enter the operator"/> 
            <property name="fieldsList" type="String" label="Fields List" description="Enter the field API names separated by coma. Do not enter more than 4 fields"/> 
        </targetConfig> 
    </targetConfigs> 
</LightningComponentBundle>

 
Best Answer chosen by The new Learner
Maharajan CMaharajan C
Hi,

1. Add the the below import file in JS:

import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';

2.  You have to set the defaultfield values in state property like below:

for example i have consider the Account ==> Opportunity scenario.
 
createNew() {

	const defaultValues = encodeDefaultFieldValues({
		AccountId: this.recordId
	});

	this[NavigationMixin.Navigate]({
		type: 'standard__objectPage',
		attributes: {
			objectApiName: this.objectName,
			actionName: 'new'
		},
		state: {
			defaultFieldValues: defaultValues
		}
	});

}


When i am reading your it's looks like as generic code . So you have to set the parent Id dynamically in defaultFieldValues. Please follow the below code:


Update your JS File:

1. You need to harcode the Parent Field API Name in below property from Appbuilder then only parent lookup will be populated. For Example AccountId is the Parent Fiedl API Name for Case,Opportunity,Contact Objects.


<property name="parentFieldAPIName" type="String" label="Parent Field API Name" description="Enter the parent field API Name"/>
 
import { LightningElement, api, wire, track } from 'lwc'; 
import fetchRecords from '@salesforce/apex/RelatedListController.fetchRecords'; 
import { NavigationMixin } from 'lightning/navigation';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';
 
export default class genericRelatedListComp extends NavigationMixin( LightningElement ) { 
 
    @api objectName; 
    @api parentObjectName;
    @api fieldName; 
    @api fieldValue; 
    @api parentFieldAPIName; 
    @api recordId; 
    @api strTitle; 
    @api filterType; 
    @api operator; 
    @api fieldsList;
    @api relationshipApiName;
    @track field1;
    @track field2;
    @track field3;
    @track field4;
    @track listRecords;
    @track titleWithCount;
    @track countBool = false;

    connectedCallback() {

        var listFields = this.fieldsList.split( ',' );
        console.log( 'Fields are ' + listFields );
        this.field1 = listFields[ 0 ].trim();
        this.field2 = listFields[ 1 ].trim();
        this.field3 = listFields[ 2 ].trim();
        this.field4 = listFields[ 3 ].trim();
        console.log( 'Field 1 is ' + this.field1 );
        console.log( 'Field 2 is ' + this.field2 );
        console.log( 'Field 3 is ' + this.field3 );
        console.log( 'Field 4 is ' + this.field4 );

    }

    get vals() { 

        return this.recordId + '-' + this.objectName + '-' +  
               this.parentFieldAPIName + '-' + this.fieldName + '-' +  
               this.fieldValue + '-' + this.filterType + '-' + this.operator + '-' + this.fieldsList; 

    } 
     
    @wire(fetchRecords, { listValues: '$vals' }) 
    accountData( { error, data } ) {

        if ( data ) {
          
            this.listRecords = data.listRecords;

            if ( data.recordCount ) {
               
                if ( data.recordCount > 3 ) {

                    this.titleWithCount = this.strTitle + '(3+)';
                    this.countBool = true;
               
                } else {

                    this.countBool = false;
                    this.titleWithCount = this.strTitle + '(' + data.recordCount + ')';

                }
            }

        }

    }

    createNew() {

        const key = this.parentFieldAPIName;
        console.log(' Parent Id --> ' + key);
        const defaultValues = encodeDefaultFieldValues({
            [key]  : this.recordId
        });
        console.log('defaultValues New --> ' + defaultValues );

        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: this.objectName,
                actionName: 'new'
            },
            state: {
                defaultFieldValues :  defaultValues
            }
        });

    }

    navigateToRelatedList() {

        this[NavigationMixin.Navigate]({
            type: 'standard__recordRelationshipPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: this.parentObjectName,
                relationshipApiName: this.relationshipApiName,
                actionName: 'view'
            }
        });

    }
 
}

Set the Parent Field API Name in App builder.

User-added image


Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi,

1. Add the the below import file in JS:

import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';

2.  You have to set the defaultfield values in state property like below:

for example i have consider the Account ==> Opportunity scenario.
 
createNew() {

	const defaultValues = encodeDefaultFieldValues({
		AccountId: this.recordId
	});

	this[NavigationMixin.Navigate]({
		type: 'standard__objectPage',
		attributes: {
			objectApiName: this.objectName,
			actionName: 'new'
		},
		state: {
			defaultFieldValues: defaultValues
		}
	});

}


When i am reading your it's looks like as generic code . So you have to set the parent Id dynamically in defaultFieldValues. Please follow the below code:


Update your JS File:

1. You need to harcode the Parent Field API Name in below property from Appbuilder then only parent lookup will be populated. For Example AccountId is the Parent Fiedl API Name for Case,Opportunity,Contact Objects.


<property name="parentFieldAPIName" type="String" label="Parent Field API Name" description="Enter the parent field API Name"/>
 
import { LightningElement, api, wire, track } from 'lwc'; 
import fetchRecords from '@salesforce/apex/RelatedListController.fetchRecords'; 
import { NavigationMixin } from 'lightning/navigation';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';
 
export default class genericRelatedListComp extends NavigationMixin( LightningElement ) { 
 
    @api objectName; 
    @api parentObjectName;
    @api fieldName; 
    @api fieldValue; 
    @api parentFieldAPIName; 
    @api recordId; 
    @api strTitle; 
    @api filterType; 
    @api operator; 
    @api fieldsList;
    @api relationshipApiName;
    @track field1;
    @track field2;
    @track field3;
    @track field4;
    @track listRecords;
    @track titleWithCount;
    @track countBool = false;

    connectedCallback() {

        var listFields = this.fieldsList.split( ',' );
        console.log( 'Fields are ' + listFields );
        this.field1 = listFields[ 0 ].trim();
        this.field2 = listFields[ 1 ].trim();
        this.field3 = listFields[ 2 ].trim();
        this.field4 = listFields[ 3 ].trim();
        console.log( 'Field 1 is ' + this.field1 );
        console.log( 'Field 2 is ' + this.field2 );
        console.log( 'Field 3 is ' + this.field3 );
        console.log( 'Field 4 is ' + this.field4 );

    }

    get vals() { 

        return this.recordId + '-' + this.objectName + '-' +  
               this.parentFieldAPIName + '-' + this.fieldName + '-' +  
               this.fieldValue + '-' + this.filterType + '-' + this.operator + '-' + this.fieldsList; 

    } 
     
    @wire(fetchRecords, { listValues: '$vals' }) 
    accountData( { error, data } ) {

        if ( data ) {
          
            this.listRecords = data.listRecords;

            if ( data.recordCount ) {
               
                if ( data.recordCount > 3 ) {

                    this.titleWithCount = this.strTitle + '(3+)';
                    this.countBool = true;
               
                } else {

                    this.countBool = false;
                    this.titleWithCount = this.strTitle + '(' + data.recordCount + ')';

                }
            }

        }

    }

    createNew() {

        const key = this.parentFieldAPIName;
        console.log(' Parent Id --> ' + key);
        const defaultValues = encodeDefaultFieldValues({
            [key]  : this.recordId
        });
        console.log('defaultValues New --> ' + defaultValues );

        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: this.objectName,
                actionName: 'new'
            },
            state: {
                defaultFieldValues :  defaultValues
            }
        });

    }

    navigateToRelatedList() {

        this[NavigationMixin.Navigate]({
            type: 'standard__recordRelationshipPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: this.parentObjectName,
                relationshipApiName: this.relationshipApiName,
                actionName: 'view'
            }
        });

    }
 
}

Set the Parent Field API Name in App builder.

User-added image


Thanks,
Maharajan.C
This was selected as the best answer
The new LearnerThe new Learner
Hi MahaRajan,

THakns for the reply, can I Use this generic code for the opportunity Product creation kindly help me out please
Maharajan CMaharajan C
Yes, you can do for the Opportunity Product. 

Set the OpportunityId in Parent Field API Name from Lightning App builder.

Also set the Other Component Properties as below in Lightning Edit Page :

Title : Opportunity Product

objectName : OpportunityLineItem 

parentObjectName : Opportunity

relationshipApiName : OpportunityLineItems

parentFieldAPIName : OpportunityId

Field Name :  Name

Field Value:  null

Filter Type:  text

Operator:   !=

Fields List :   Product2,Quantity,UnitPrice,ListPrice


Thanks,
Maharajan.C

 
The new LearnerThe new Learner
Thanks for getting back to me for the replay if I want display productid as a dafult value then what I have to do
Maharajan CMaharajan C
Are you addding this component in Opportunity Deatil Page or Product Detail Page?

 
The new LearnerThe new Learner
Opportunity detail page
Maharajan CMaharajan C
Where you want to show the productid as a dafult value ?

Please share the screenshot with your current progress
The new LearnerThe new Learner
I have applied the same code however, it was added the same code
The new LearnerThe new Learner
Hi @maharajan

its not working, its throwing an error like below on selection of product.


Unfortunately, there was a problem. Please try again. If the problem continues, get in touch with your administrator with the error ID shown here and any other related details. Error ID: 850795159-227537 (-950221959)
bosow kevinbosow kevin

I'm really happy I was can to improve insights from this great Information 
Tescoviews (https://gab.com/Dferthuj/posts/110608976498230447)